Skip to content

"rsync for cloud storage" - Google Drive, S3, Dropbox, Backblaze B2, One Drive, Swift, Hubic, Wasabi, Google Cloud Storage, Azure Blob, Azure Files, Yandex Files

vfs: add Hold to keep a VFS from being shut down while in use

Nick Craig-Wood1dab0f3abd3d
diff --git a/vfs/vfs.go b/vfs/vfs.go
index ec3761972..31116c822 100644
--- a/vfs/vfs.go
+++ b/vfs/vfs.go
@@ -395,6 +395,21 @@ func (vfs *VFS) shutdownCache() {
}
}
+// Hold takes another reference to the VFS so it isn't shut down until
+// a matching call to Shutdown. It returns false, taking no reference,
+// if the VFS has already been shut down.
+func (vfs *VFS) Hold() bool {
+ for {
+ n := vfs.inUse.Load()
+ if n <= 0 {
+ return false
+ }
+ if vfs.inUse.CompareAndSwap(n, n+1) {
+ return true
+ }
+ }
+}
+
// Shutdown stops any background go-routines and removes the VFS from
// the active ache.
func (vfs *VFS) Shutdown() {
diff --git a/vfs/vfs_test.go b/vfs/vfs_test.go
index 03613a25e..c9f9f95cf 100644
--- a/vfs/vfs_test.go
+++ b/vfs/vfs_test.go
@@ -159,6 +159,21 @@ func TestVFSNew(t *testing.T) {
checkActiveCacheEntries(0)
}
+// TestVFSHold checks a held VFS isn't shut down until it is released
+// and can't be held once shut down.
+func TestVFSHold(t *testing.T) {
+ r := fstest.NewRun(t)
+ vfs := New(context.Background(), r.Fremote, nil)
+
+ require.True(t, vfs.Hold())
+ vfs.Shutdown()
+ assert.NoError(t, vfs.ctx.Err(), "VFS shut down while held")
+
+ vfs.Shutdown()
+ assert.Error(t, vfs.ctx.Err(), "VFS not shut down when released")
+ assert.False(t, vfs.Hold(), "VFS held after being shut down")
+}
+
// TestVFSNewWithOpts sees if the New command works properly
func TestVFSNewWithOpts(t *testing.T) {
var opt = vfscommon.Opt