delete.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package infra
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "github.com/porter-dev/porter/api/server/handlers"
  7. "github.com/porter-dev/porter/api/server/shared"
  8. "github.com/porter-dev/porter/api/server/shared/apierrors"
  9. "github.com/porter-dev/porter/api/server/shared/config"
  10. "github.com/porter-dev/porter/api/types"
  11. "github.com/porter-dev/porter/internal/models"
  12. ptypes "github.com/porter-dev/porter/provisioner/types"
  13. )
  14. type InfraDeleteHandler struct {
  15. handlers.PorterHandlerReadWriter
  16. }
  17. func NewInfraDeleteHandler(
  18. config *config.Config,
  19. decoderValidator shared.RequestDecoderValidator,
  20. writer shared.ResultWriter,
  21. ) *InfraDeleteHandler {
  22. return &InfraDeleteHandler{
  23. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  24. }
  25. }
  26. func (c *InfraDeleteHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  27. ctx := r.Context()
  28. proj, _ := ctx.Value(types.ProjectScope).(*models.Project)
  29. infra, _ := ctx.Value(types.InfraScope).(*models.Infra)
  30. req := &types.DeleteInfraRequest{}
  31. if ok := c.DecodeAndValidate(w, r, req); !ok {
  32. return
  33. }
  34. // verify the credentials
  35. err := checkInfraCredentials(c.Config(), proj, infra, req.InfraCredentials)
  36. if err != nil {
  37. c.HandleAPIError(w, r, apierrors.NewErrForbidden(err))
  38. return
  39. }
  40. lastOperation, err := c.Repo().Infra().GetLatestOperation(infra)
  41. if err != nil {
  42. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  43. return
  44. }
  45. // if the last operation is in a "starting" state, block apply
  46. if lastOperation.Status == "starting" {
  47. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  48. fmt.Errorf("Operation currently in progress. Please try again when latest operation has completed."),
  49. http.StatusBadRequest,
  50. ))
  51. return
  52. }
  53. // mark the infra as destroying
  54. infra.Status = types.StatusDestroying
  55. infra, err = c.Repo().Infra().UpdateInfra(infra)
  56. if err != nil {
  57. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  58. return
  59. }
  60. // call apply on the provisioner service
  61. resp, err := c.Config().ProvisionerClient.Delete(context.Background(), proj.ID, infra.ID, &ptypes.DeleteBaseRequest{
  62. OperationKind: "delete",
  63. })
  64. if err != nil {
  65. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  66. return
  67. }
  68. c.WriteResult(w, r, resp)
  69. }