diff --git a/cmd/backsnap/backup.go b/cmd/backsnap/backup.go index b207579..28f6ff6 100644 --- a/cmd/backsnap/backup.go +++ b/cmd/backsnap/backup.go @@ -119,6 +119,17 @@ func BackupPvc(ctx context.Context, clientset kubernetes.Interface, kclient clie } } + // Check whether the target PVC exists + targetPvc := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: namespace, + Name: pvcName, + }, + } + if err := kclient.Get(ctx, client.ObjectKeyFromObject(targetPvc), targetPvc); err != nil { + return err + } + var snapshotClass *string if settings.SnapshotClass != "" { snapshotClass = &settings.SnapshotClass @@ -188,6 +199,10 @@ func BackupPvc(ctx context.Context, clientset kubernetes.Interface, kclient clie time.Sleep(time.Second) } + + if ctx.Err() != nil { + return ctx.Err() + } } slog.InfoContext(ctx, "volumesnapshot is ready!", diff --git a/cmd/backsnap/backup_test.go b/cmd/backsnap/backup_test.go new file mode 100644 index 0000000..4351d89 --- /dev/null +++ b/cmd/backsnap/backup_test.go @@ -0,0 +1,34 @@ +package main_test + +import ( + "context" + "testing" + + volumesnapshotv1 "github.com/kubernetes-csi/external-snapshotter/client/v6/apis/volumesnapshot/v1" + backsnap "github.com/skybitsnl/backsnap/cmd/backsnap" + batchv1 "k8s.io/api/batch/v1" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/runtime" + dynamicfake "k8s.io/client-go/dynamic/fake" + oldfake "k8s.io/client-go/kubernetes/fake" + "sigs.k8s.io/controller-runtime/pkg/client/fake" +) + +func TestBackupPVC_DoesntExist(t *testing.T) { + ctx := context.Background() + + scheme := runtime.NewScheme() + corev1.AddToScheme(scheme) + batchv1.AddToScheme(scheme) + volumesnapshotv1.AddToScheme(scheme) + + clientset := oldfake.NewSimpleClientset() + kclient := fake.NewClientBuilder().WithScheme(scheme).Build() + dynamicClient := dynamicfake.NewSimpleDynamicClient(scheme) + + err := backsnap.BackupPvc(ctx, clientset, kclient, dynamicClient, "app1", "my-storage", backsnap.BackupSettings{}) + if !errors.IsNotFound(err) { + t.Fatalf("expected Not Found error, but got: %+v", err) + } +}