From a4b2facd919ecb8c27c58aded92a6623b878c24f Mon Sep 17 00:00:00 2001 From: b0m313 <13.spring.03@gmail.com> Date: Wed, 13 Dec 2023 21:40:27 +0000 Subject: [PATCH] feat(cleanup): Add resource cleanup --- Nimbus/controllers/cleanup/cleanup.go | 55 +++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Nimbus/controllers/cleanup/cleanup.go diff --git a/Nimbus/controllers/cleanup/cleanup.go b/Nimbus/controllers/cleanup/cleanup.go new file mode 100644 index 00000000..4c892d35 --- /dev/null +++ b/Nimbus/controllers/cleanup/cleanup.go @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2023 Authors of Nimbus + +package cleanup + +import ( + "context" + + "github.com/go-logr/logr" + "sigs.k8s.io/controller-runtime/pkg/client" + + intentv1 "github.com/5GSEC/nimbus/Nimbus/api/v1" + general "github.com/5GSEC/nimbus/Nimbus/controllers/general" + policy "github.com/5GSEC/nimbus/Nimbus/controllers/policy" +) + +// Cleanup is a function to clean up SecurityIntent resources. +// It removes all policies associated with each SecurityIntent before deleting the SecurityIntent itself. +func Cleanup(ctx context.Context, k8sClient client.Client, logger logr.Logger) error { + + // Logging the start of the cleanup process. + logger.Info("Performing cleanup") + + var securityIntentBindings intentv1.SecurityIntentBindingList + if err := k8sClient.List(ctx, &securityIntentBindings); err != nil { + logger.Error(err, "Unable to list SecurityIntentBinding resources for cleanup") + return err + } + + if len(securityIntentBindings.Items) == 0 { + logger.Info("No SecurityIntentBinding resources found for cleanup") + return nil + } + + npc := policy.NewNetworkPolicyController(k8sClient, nil) + + // Iterating over each SecurityIntent to delete associated policies. + for _, binding := range securityIntentBindings.Items { + + bindingInfo := &general.BindingInfo{ + Binding: &binding, + } + + // Deleting network policies associated with the current SecurityIntent. + if err := npc.DeletePolicy(ctx, bindingInfo); err != nil { + logger.Error(err, "Failed to delete network policy for SecurityIntentBinding", "Name", binding.Name) + return err + } + if err := k8sClient.Delete(ctx, &binding); err != nil { + logger.Error(err, "Failed to delete SecurityIntentBinding", "Name", binding.Name) + continue + } + } + return nil +}