2
0

create_deployment_by_cluster.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. package environment
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "github.com/porter-dev/porter/internal/telemetry"
  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/config"
  12. "github.com/porter-dev/porter/api/types"
  13. "github.com/porter-dev/porter/internal/models"
  14. "gorm.io/gorm"
  15. )
  16. type CreateDeploymentByClusterHandler struct {
  17. handlers.PorterHandlerReadWriter
  18. authz.KubernetesAgentGetter
  19. }
  20. func NewCreateDeploymentByClusterHandler(
  21. config *config.Config,
  22. decoderValidator shared.RequestDecoderValidator,
  23. writer shared.ResultWriter,
  24. ) *CreateDeploymentByClusterHandler {
  25. return &CreateDeploymentByClusterHandler{
  26. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  27. KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
  28. }
  29. }
  30. func (c *CreateDeploymentByClusterHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  31. ctx, span := telemetry.NewSpan(r.Context(), "serve-create-deployment-by-cluster")
  32. defer span.End()
  33. project, _ := ctx.Value(types.ProjectScope).(*models.Project)
  34. cluster, _ := ctx.Value(types.ClusterScope).(*models.Cluster)
  35. telemetry.WithAttributes(span,
  36. telemetry.AttributeKV{Key: "project-id", Value: project.ID},
  37. telemetry.AttributeKV{Key: "cluster-id", Value: cluster.ID},
  38. )
  39. request := &types.CreateDeploymentRequest{}
  40. if ok := c.DecodeAndValidate(w, r, request); !ok {
  41. err := telemetry.Error(ctx, span, nil, "could not decode and validate request")
  42. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  43. return
  44. }
  45. telemetry.WithAttributes(span,
  46. telemetry.AttributeKV{Key: "repo-owner", Value: request.RepoOwner},
  47. telemetry.AttributeKV{Key: "repo-name", Value: request.RepoName},
  48. telemetry.AttributeKV{Key: "namespace", Value: request.Namespace},
  49. telemetry.AttributeKV{Key: "pull-request-id", Value: request.PullRequestID},
  50. telemetry.AttributeKV{Key: "pr-name", Value: request.GitHubMetadata.PRName},
  51. telemetry.AttributeKV{Key: "commit-sha", Value: request.GitHubMetadata.CommitSHA},
  52. telemetry.AttributeKV{Key: "pr-branch-from", Value: request.GitHubMetadata.PRBranchFrom},
  53. telemetry.AttributeKV{Key: "pr-branch-into", Value: request.GitHubMetadata.PRBranchInto},
  54. )
  55. // read the environment to get the environment id
  56. env, err := c.Repo().Environment().ReadEnvironmentByOwnerRepoName(
  57. project.ID, cluster.ID, request.RepoOwner, request.RepoName,
  58. )
  59. if err != nil {
  60. err = telemetry.Error(ctx, span, err, "error reading environment by owner repo name")
  61. if errors.Is(err, gorm.ErrRecordNotFound) {
  62. c.HandleAPIError(w, r, apierrors.NewErrNotFound(
  63. fmt.Errorf("error creating deployment: %w", errEnvironmentNotFound)),
  64. )
  65. return
  66. }
  67. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  68. return
  69. }
  70. // create deployment on GitHub API
  71. client, err := getGithubClientFromEnvironment(c.Config(), env)
  72. if err != nil {
  73. err = telemetry.Error(ctx, span, err, "error getting github client from environment")
  74. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  75. return
  76. }
  77. // add a check for Github PR status
  78. prClosed, err := isGithubPRClosed(client, request.RepoOwner, request.RepoName, int(request.PullRequestID))
  79. if err != nil {
  80. err = telemetry.Error(ctx, span, err, "error checking if github pr is closed")
  81. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusConflict))
  82. return
  83. }
  84. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "pr-closed", Value: prClosed})
  85. if prClosed {
  86. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "unsuccessful-exit-reason", Value: "pr is closed"})
  87. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  88. fmt.Errorf("attempting to create deployment for a closed github PR"), http.StatusConflict,
  89. ))
  90. return
  91. }
  92. ghDeployment, err := createGithubDeployment(client, env, request.PRBranchFrom, request.ActionID)
  93. if err != nil {
  94. err = telemetry.Error(ctx, span, err, "error creating github deployment object")
  95. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusConflict))
  96. return
  97. }
  98. // create the deployment
  99. depl, err := c.Repo().Environment().CreateDeployment(&models.Deployment{
  100. EnvironmentID: env.ID,
  101. Namespace: request.Namespace,
  102. Status: types.DeploymentStatusCreating,
  103. PullRequestID: request.PullRequestID,
  104. GHDeploymentID: ghDeployment.GetID(),
  105. RepoOwner: request.GitHubMetadata.RepoOwner,
  106. RepoName: request.GitHubMetadata.RepoName,
  107. PRName: request.GitHubMetadata.PRName,
  108. CommitSHA: request.GitHubMetadata.CommitSHA,
  109. PRBranchFrom: request.GitHubMetadata.PRBranchFrom,
  110. PRBranchInto: request.GitHubMetadata.PRBranchInto,
  111. })
  112. if err != nil {
  113. err = telemetry.Error(ctx, span, err, "error creating github deployment object")
  114. // try to delete the GitHub deployment
  115. _, deleteErr := client.Repositories.DeleteDeployment(
  116. ctx,
  117. env.GitRepoOwner,
  118. env.GitRepoName,
  119. ghDeployment.GetID(),
  120. )
  121. if deleteErr != nil {
  122. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "delete-err", Value: deleteErr.Error()})
  123. }
  124. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error creating deployment: %w", err)))
  125. return
  126. }
  127. c.WriteResult(w, r, depl.ToDeploymentType())
  128. }