Moving a directory atomically

Viewed 16604

I have two directories in the same parent directory. Call the parent directory base and the children directories alpha and bravo. I want to replace alpha with bravo. The simplest method is:

rm -rf alpha
mv bravo alpha

The mv command is atomic, but the rm -rf is not. Is there a simple way in bash to atomically replace alpha with bravo? If not, is there a complicated way?

ADDENDUM:

By the by, it's not an insurmountable problem if the directory doesn't exist for a short period. There's only one place that tries to access alpha, and it checks if alpha exists before doing anything critical. If not, it gives an error message. But it would be nice if there was a way to do this. :) Maybe there's some way to modify the inodes directly, or something...

16 Answers

You can do this if you use symlinks:

Let's say alpha is a symlink to directory alpha_1, and you want to switch the symlink to point to alpha_2. Here's what that looks like before the switch:

$ ls -l
lrwxrwxrwx alpha -> alpha_1
drwxr-xr-x alpha_1
drwxr-xr-x alpha_2

To make alpha refer to alpha_2, use ln -nsf:

$ ln -nsf alpha_2 alpha
$ ls -l
lrwxrwxrwx alpha -> alpha_2
drwxr-xr-x alpha_1
drwxr-xr-x alpha_2

Now you can remove the old directory:

$ rm -rf alpha_1

Note that this is NOT actually a fully atomic operation, but it does happen very quickly since the "ln" command both unlinks and then immediately recreates the symlink. You can verify this behaviour with strace:

$ strace ln -nsf alpha_2 alpha
...
symlink("alpha_2", "alpha")             = -1 EEXIST (File exists)
unlink("alpha")                         = 0
symlink("alpha_2", "alpha")             = 0
...

You can repeat this procedure as desired: e.g. when you have a new version, alpha_3:

$ ln -nsf alpha_3 alpha
$ rm -rf alpha_2

Since Linux 3.15, the new renameat2 system call can atomically exchange two paths on the same file system. However, there’s not even a glibc wrapper for it yet, let alone a coreutils way to access it. So it would look something like this:

int dirfd = open(".../base", O_PATH | O_DIRECTORY | O_CLOEXEC);
syscall(SYS_renameat2, dirfd, "alpha", dirfd, "bravo", RENAME_EXCHANGE);
close(dirfd);
system("rm -rf alpha");

(Of course, you should do proper error handling etc. – see this gist for a more sophisticated renameat2 wrapper.)

That said – the symlink solution mentioned by others is both easier and portable, so unless bravo already exists and you must atomically update it, go with the symlink instead.


2020 update: a glibc wrapper for this system call is available since glibc 2.28, released 2018-08-01 (Debian Stretch, Fedora 29). It’s still not accessible via coreutils, though.

int dirfd = open(".../base", O_PATH | O_DIRECTORY | O_CLOEXEC);
renameat2(dirfd, "alpha", dirfd, "bravo", RENAME_EXCHANGE);
close(dirfd);
system("rm -rf alpha");

Use a separate, guaranteed atomic, operation to act as a semaphore.

So, if the creating and removing a file operations are atomic:

1) create a file called "semaphore".

2) If and only if that is successful (no conflict with existing file), do the operation (either process alpha or move the directory, depending on the process)

3) rm semaphore.

If you mean atomic across both operations, I don't believe so. The closest would be:

mv alpha delta
mv bravo alpha
rm -rf delta

but that would still have a small window where alpha didn't exist.

To minimize the likelihood of anything trying to use alpha while it's not there you could (if you have the authority):

nice --20 ( mv alpha delta ; mv bravo alpha )
rm -rf delta

which will crank up your process priority substantially while the mv operations are happening.

If, as you say in your addendum, there's only one place that checks alpha and it errors if it's not there, you could change that code to not error immediately, but try again in a short time (easily sub-second for two mv operations) - these retries should alleviate any problem unless you're replacing alpha very frequently.

Even if you were accessing the inodes directly there would still be no way to atomically swap the inode values in user-space.

Worrying about the atomic nature of the operation is meaningless. The thing is, the access to alpha by the other task will not be atomic anyway.

Oddthinking's semaphore approach is the only way to go.

If you can't modify the other task then you'll have to ensure it's not running before doing the replacement.

I don't believe there's any atomic way to do this. Your best bet is to do something like this:

mv alpha delme
mv bravo alpha
rm -rf delme

Something to keep in mind is that if your process has any of the files in alpha open when this move/delete occurs the process will not notice and any data written will be lost when the file is closed and finally removed.

It is also possible to replace a whole parts of the content at once in some prefix (Z here) using unionfs-fuse:

# mkdir a b c Z
# touch a/1 b/2 c/3
# ln -s a X
# ln -s b Y
# unionfs X=RW:Y=RW Z
# shopt -s globstar
# file **
a:   directory
a/1: empty
b:   directory
b/2: empty
c:   directory
c/3: empty
X:   symbolic link to a
Y:   symbolic link to b
Z:   directory
Z/1: empty
Z/2: empty
# ln -sfn c Y
# file **/*
a:   directory
a/1: empty
b:   directory
b/2: empty
c:   directory
c/3: empty
X:   symbolic link to a
X/1: empty
Y:   symbolic link to c
Y/3: empty
Z:   directory
Z/1: empty
Z/3: empty
# fusermount -u Z
# rm -r a b c X Y Z

mount --bind bravo alpha should do this on Linux

It leaves the contents of alpha hidden but you can bind mount the parent filesystem elsewhere if you want to clean it out.

If the filesystem is NFS exported you would likely need to ensure the export options allowed crossing filesystem boundaries and do the bind mount on the server.

You also need to be careful about processes that have an open handle on the alpha directory or subdirectory (eg cwd).

Other *nix may have similar tricks up their sleeves but it isn't standardised.

Why don't you just do something like:

rm -rf alpha/*
mv bravo/* alpha/
rm -rf bravo/

That would mean that everything in alpha is destroyed, alpha never gets deleted, and all the contents get moved.

Related