From 660420bdf4e0d126ac145ef6496ecea29922cbe4 Mon Sep 17 00:00:00 2001 From: Mauricio Poppe Date: Thu, 22 Apr 2021 00:45:19 +0000 Subject: [PATCH] Make sure the VolumeSnapshots v1 CRDs exist before starting the controller --- cmd/snapshot-controller/main.go | 48 +++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/cmd/snapshot-controller/main.go b/cmd/snapshot-controller/main.go index ad045e0e0..6d94f9fde 100644 --- a/cmd/snapshot-controller/main.go +++ b/cmd/snapshot-controller/main.go @@ -29,6 +29,10 @@ import ( "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/wait" + klog "k8s.io/klog/v2" "github.com/kubernetes-csi/csi-lib-utils/leaderelection" @@ -59,6 +63,45 @@ var ( version = "unknown" ) +// Checks that the VolumeSnapshot v1 CRDs exist. +func ensureCustomResourceDefinitionsExist(kubeClient *kubernetes.Clientset, client *clientset.Clientset) error { + condition := func() (bool, error) { + var err error + _, err = kubeClient.CoreV1().Namespaces().Get(context.TODO(), "kube-system", metav1.GetOptions{}) + if err != nil { + // only execute list VolumeSnapshots if the kube-system namespace exists + _, err = client.SnapshotV1().VolumeSnapshots("kube-system").List(context.TODO(), metav1.ListOptions{}) + if err != nil { + klog.Errorf("Failed to list v1 volumesnapshots with error=%+v", err) + return false, nil + } + } + _, err = client.SnapshotV1().VolumeSnapshotClasses().List(context.TODO(), metav1.ListOptions{}) + if err != nil { + klog.Errorf("Failed to list v1 volumesnapshotclasses with error=%+v", err) + return false, nil + } + _, err = client.SnapshotV1().VolumeSnapshotContents().List(context.TODO(), metav1.ListOptions{}) + if err != nil { + klog.Errorf("Failed to list v1 volumesnapshotcontents with error=%+v", err) + return false, nil + } + return true, nil + } + + // with a Factor of 1.5 we wait up to 7.5 seconds (the 10th attempt) + backoff := wait.Backoff{ + Duration: 100 * time.Millisecond, + Factor: 1.5, + Steps: 10, + } + if err := wait.ExponentialBackoff(backoff, condition); err != nil { + return err + } + + return nil +} + func main() { klog.InitFlags(nil) flag.Set("logtostderr", "true") @@ -130,6 +173,11 @@ func main() { *resyncPeriod, ) + if err := ensureCustomResourceDefinitionsExist(kubeClient, snapClient); err != nil { + klog.Errorf("Exiting due to failure to ensure CRDs exist during startup: %+v", err) + os.Exit(1) + } + run := func(context.Context) { // run... stopCh := make(chan struct{})