delete.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package environment_groups
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/porter-dev/porter/internal/kubernetes"
  6. "github.com/porter-dev/porter/internal/telemetry"
  7. k8serror "k8s.io/apimachinery/pkg/api/errors"
  8. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  9. )
  10. // DeleteEnvironmentGroup deletes an environment group and all of its versions from all namespaces, only if there are no linked applications
  11. func DeleteEnvironmentGroup(ctx context.Context, a *kubernetes.Agent, name string) error {
  12. ctx, span := telemetry.NewSpan(ctx, "delete-environment-groups")
  13. defer span.End()
  14. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "environment-group", Value: name})
  15. if name == "" {
  16. return telemetry.Error(ctx, span, nil, "environment group name cannot be empty")
  17. }
  18. environmentGroups, err := ListEnvironmentGroups(ctx, a, WithEnvironmentGroupName(name), WithNamespace(Namespace_EnvironmentGroups))
  19. if err != nil {
  20. return telemetry.Error(ctx, span, err, "unable to list environment groups")
  21. }
  22. for _, environmentGroup := range environmentGroups {
  23. applications, err := LinkedApplications(ctx, a, environmentGroup.Name, true)
  24. if err != nil {
  25. return telemetry.Error(ctx, span, err, "unable to list linked applications")
  26. }
  27. if len(applications) > 0 {
  28. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "linked-applications", Value: len(applications)})
  29. return telemetry.Error(ctx, span, nil, "unable to delete environment group with linked applications")
  30. }
  31. }
  32. allConfigMapsInAllNamespaces, err := a.Clientset.CoreV1().ConfigMaps(metav1.NamespaceAll).List(ctx,
  33. metav1.ListOptions{LabelSelector: fmt.Sprintf("%s=%s", LabelKey_EnvironmentGroupName, name)},
  34. )
  35. if err != nil {
  36. return telemetry.Error(ctx, span, err, "unable to list environment group variables")
  37. }
  38. for _, val := range allConfigMapsInAllNamespaces.Items {
  39. labelName := fmt.Sprintf("%s.%s", val.Labels[LabelKey_EnvironmentGroupName], val.Labels[LabelKey_EnvironmentGroupVersion])
  40. err := a.Clientset.CoreV1().ConfigMaps(val.Namespace).Delete(ctx,
  41. labelName,
  42. metav1.DeleteOptions{},
  43. )
  44. if err != nil {
  45. if !k8serror.IsNotFound(err) {
  46. return telemetry.Error(ctx, span, err, "unable to delete environment group variables")
  47. }
  48. }
  49. err = a.Clientset.CoreV1().Secrets(val.Namespace).Delete(ctx,
  50. labelName,
  51. metav1.DeleteOptions{},
  52. )
  53. if err != nil {
  54. if !k8serror.IsNotFound(err) {
  55. return telemetry.Error(ctx, span, err, "unable to delete environment group secret variables")
  56. }
  57. }
  58. }
  59. return nil
  60. }