Managing finalizers and deletion in Go applications, especially in Kubernetes custom controllers, is vital for ensuring resources are cleaned up properly. Finalizers allow you to execute custom logic before a resource is fully deleted. Below is an example showing how to implement finalizers in a Go-based controller.
package main
import (
"context"
"fmt"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
type MyResource struct {
Name string
Finalizer string
}
func main() {
kubeconfig := "path/to/your/kubeconfig"
config, _ := clientcmd.BuildConfigFromFlags("", kubeconfig)
clientset, _ := kubernetes.NewForConfig(config)
// Example of adding a finalizer
resource := &MyResource{
Name: "example-resource",
Finalizer: "example.finalizer.com",
}
// Simulate resource deletion
if err := deleteResourceWithFinalizer(clientset, resource); err != nil {
fmt.Println(err)
}
}
func deleteResourceWithFinalizer(clientset *kubernetes.Clientset, resource *MyResource) error {
// Check if the resource has a finalizer
if resource.Finalizer != "" {
// Perform cleanup before deleting
fmt.Println("Cleaning up resource:", resource.Name)
time.Sleep(2 * time.Second) // Simulating cleanup process
// After cleanup, remove finalizer
resource.Finalizer = ""
fmt.Println("Finalizer removed, resource deleted:", resource.Name)
}
return nil
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?