Skip to content

A platform for community discussion. Free, open, simple.

FIX: Restore cross-filesystem fallback in atomic_ln_s (Errno::EXDEV) (#41330)

Elias Hackradtb607e0b12eee
diff --git a/lib/discourse.rb b/lib/discourse.rb
index 0c48ad46067..d7d45346011 100644
--- a/lib/discourse.rb
+++ b/lib/discourse.rb
@@ -115,7 +115,17 @@ module Discourse
temp_destination = Rails.root.join("tmp", SecureRandom.hex).to_s
execute_command("ln", "-s", source, temp_destination)
- File.rename(temp_destination, destination)
+
+ begin
+ File.rename(temp_destination, destination)
+ rescue Errno::EXDEV
+ # Rails.root/tmp and the destination can live on different filesystems
+ # (e.g. containerized setups where tmp is a separate mount). rename(2)
+ # cannot cross filesystem boundaries, so fall back to a non-atomic
+ # replace. The flock above already serializes writers.
+ File.delete(destination) if File.symlink?(destination)
+ FileUtils.mv(temp_destination, destination)
+ end
end
nil
diff --git a/spec/lib/discourse_spec.rb b/spec/lib/discourse_spec.rb
index 2488bc7963c..468f931a007 100644
--- a/spec/lib/discourse_spec.rb
+++ b/spec/lib/discourse_spec.rb
@@ -631,6 +631,45 @@ RSpec.describe Discourse do
end
end
+ describe "Utils.atomic_ln_s" do
+ let(:source) { Dir.mktmpdir }
+
+ it "creates the destination symlink pointing at the source" do
+ Dir.mktmpdir do |dir|
+ destination = File.join(dir, "link")
+ Discourse::Utils.atomic_ln_s(source, destination)
+
+ expect(File.symlink?(destination)).to eq(true)
+ expect(File.readlink(destination)).to eq(source)
+ end
+ end
+
+ it "replaces an existing symlink at the destination" do
+ Dir.mktmpdir do |dir|
+ destination = File.join(dir, "link")
+ File.symlink(Dir.mktmpdir, destination)
+
+ Discourse::Utils.atomic_ln_s(source, destination)
+
+ expect(File.readlink(destination)).to eq(source)
+ end
+ end
+
+ it "falls back to a copy when tmp and destination are on different filesystems" do
+ # rename(2) raises EXDEV across filesystem boundaries (e.g. containers
+ # where Rails.root/tmp is a separate mount). The link must still land.
+ Dir.mktmpdir do |dir|
+ destination = File.join(dir, "link")
+ allow(File).to receive(:rename).and_raise(Errno::EXDEV)
+
+ Discourse::Utils.atomic_ln_s(source, destination)
+
+ expect(File.symlink?(destination)).to eq(true)
+ expect(File.readlink(destination)).to eq(source)
+ end
+ end
+ end
+
describe ".clear_all_theme_cache!" do
before do
setup_s3