delete.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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/integrations/ci/actions"
  16. "github.com/porter-dev/porter/internal/models"
  17. "github.com/porter-dev/porter/internal/models/integrations"
  18. "gorm.io/gorm"
  19. )
  20. type DeleteEnvironmentHandler struct {
  21. handlers.PorterHandlerReadWriter
  22. authz.KubernetesAgentGetter
  23. }
  24. func NewDeleteEnvironmentHandler(
  25. config *config.Config,
  26. decoderValidator shared.RequestDecoderValidator,
  27. writer shared.ResultWriter,
  28. ) *DeleteEnvironmentHandler {
  29. return &DeleteEnvironmentHandler{
  30. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  31. KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
  32. }
  33. }
  34. func (c *DeleteEnvironmentHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  35. ga, _ := r.Context().Value(types.GitInstallationScope).(*integrations.GithubAppInstallation)
  36. project, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  37. cluster, _ := r.Context().Value(types.ClusterScope).(*models.Cluster)
  38. if !project.PreviewEnvsEnabled {
  39. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(errPreviewProjectDisabled, http.StatusForbidden))
  40. return
  41. } else if !cluster.PreviewEnvsEnabled {
  42. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(errPreviewClusterDisabled, http.StatusForbidden))
  43. return
  44. }
  45. owner, name, ok := commonutils.GetOwnerAndNameParams(c, w, r)
  46. if !ok {
  47. return
  48. }
  49. // read the environment to get the environment id
  50. env, err := c.Repo().Environment().ReadEnvironment(project.ID, cluster.ID, uint(ga.InstallationID), owner, name)
  51. if err != nil {
  52. if errors.Is(err, gorm.ErrRecordNotFound) {
  53. c.HandleAPIError(w, r, apierrors.NewErrNotFound(errEnvironmentNotFound))
  54. return
  55. }
  56. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  57. return
  58. }
  59. // delete all corresponding deployments
  60. agent, err := c.GetAgent(r, cluster, "")
  61. if err != nil {
  62. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  63. return
  64. }
  65. depls, err := c.Repo().Environment().ListDeployments(env.ID)
  66. if err != nil {
  67. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  68. return
  69. }
  70. for _, depl := range depls {
  71. if !isSystemNamespace(depl.Namespace) {
  72. agent.DeleteNamespace(depl.Namespace)
  73. }
  74. }
  75. ghWebhookID := env.GithubWebhookID
  76. webhookUID := env.WebhookID
  77. // delete the environment
  78. env, err = c.Repo().Environment().DeleteEnvironment(env)
  79. if err != nil {
  80. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  81. return
  82. }
  83. client, err := getGithubClientFromEnvironment(c.Config(), env)
  84. if err != nil {
  85. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  86. return
  87. }
  88. // FIXME: ignore the return status codes for now, should be fixed when we start returning all non-fatal errors
  89. if ghWebhookID != 0 {
  90. client.Repositories.DeleteHook(context.Background(), owner, name, ghWebhookID)
  91. } else {
  92. webhookURL := getGithubWebhookURLFromUID(c.Config().ServerConf.ServerURL, string(webhookUID))
  93. // FIXME: should be cycling through all webhooks if pagination is needed
  94. hooks, _, err := client.Repositories.ListHooks(context.Background(), owner, name, &github.ListOptions{})
  95. if err == nil {
  96. for _, hook := range hooks {
  97. if hookURL, ok := hook.Config["url"]; ok {
  98. if hookURLStr, ok := hookURL.(string); ok {
  99. if hookURLStr == webhookURL {
  100. client.Repositories.DeleteHook(context.Background(), owner, name, hook.GetID())
  101. break
  102. }
  103. }
  104. }
  105. }
  106. }
  107. }
  108. err = actions.DeleteEnv(&actions.EnvOpts{
  109. Client: client,
  110. ServerURL: c.Config().ServerConf.ServerURL,
  111. GitRepoOwner: env.GitRepoOwner,
  112. GitRepoName: env.GitRepoName,
  113. ProjectID: project.ID,
  114. ClusterID: cluster.ID,
  115. GitInstallationID: uint(ga.InstallationID),
  116. EnvironmentName: env.Name,
  117. InstanceName: c.Config().ServerConf.InstanceName,
  118. })
  119. if err != nil {
  120. if errors.Is(err, actions.ErrProtectedBranch) {
  121. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  122. fmt.Errorf("we were unable to delete the Porter Preview Environment workflow files for this "+
  123. "repository as the default branch is protected. Please manually delete them."), http.StatusConflict,
  124. ))
  125. return
  126. }
  127. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  128. return
  129. }
  130. c.WriteResult(w, r, env.ToEnvironmentType())
  131. }