A platform for community discussion. Free, open, simple.
FEATURE: Deduplicate S3 uploads in backups using hardlinks
Jake Goldsborough2bfeb870137d
diff --git a/lib/backup_restore/backuper.rb b/lib/backup_restore/backuper.rbindex e86542cec46..ebd498fc622 100644--- a/lib/backup_restore/backuper.rb+++ b/lib/backup_restore/backuper.rb@@ -300,6 +300,9 @@ module BackupRestoreendend+ # Lightweight struct to avoid holding full ActiveRecord objects in memory+ UploadData = Struct.new(:id, :url, :sha1, keyword_init: true)+def add_remote_uploads_to_archive(tar_filename)if !SiteSetting.include_s3_uploads_in_backupslog "Skipping uploads stored on S3."@@ -308,24 +311,17 @@ module BackupRestorelog "Downloading uploads from S3. This may take a while..."- store = FileStore::S3Store.new- upload_directory = Discourse.store.upload_path- count = 0+ @s3_store = FileStore::S3Store.new+ @upload_directory = Discourse.store.upload_path+ @download_stats = { downloaded: 0, hardlinked: 0 }- Upload.find_each do |upload|- next if upload.local?- filename = File.join(@tmp_directory, upload_directory, store.get_path_for_upload(upload))+ uploads_by_sha1 = group_remote_uploads_by_sha1+ total_uploads = uploads_by_sha1.values.sum(&:size)+ log "Found #{uploads_by_sha1.size} unique files from #{total_uploads} total uploads"- begin- FileUtils.mkdir_p(File.dirname(filename))- store.download_file(upload, filename)- rescue StandardError => ex- log "Failed to download file with upload ID #{upload.id} from S3", ex- end+ uploads_by_sha1.each_value { |upload_group| process_upload_group(upload_group) }- count += 1- log "#{count} files have already been downloaded. Still downloading..." if count % 500 == 0- end+ log "Finished processing uploads: #{@download_stats[:downloaded]} downloaded, #{@download_stats[:hardlinked]} deduplicated via hardlinks"log "Appending uploads to archive..."Discourse::Utils.execute_command(@@ -333,13 +329,80 @@ module BackupRestore"--append","--file",tar_filename,- upload_directory,+ @upload_directory,failure_message: "Failed to append uploads to archive.",success_status_codes: [0, 1],chdir: @tmp_directory,)- log "No uploads found on S3. Skipping archiving of uploads stored on S3..." if count == 0+ if @download_stats[:downloaded] == 0 && @download_stats[:hardlinked] == 0+ log "No uploads found on S3. Skipping archiving of uploads stored on S3..."+ end+ end++ def group_remote_uploads_by_sha1+ # Filter remote uploads at DB level and pluck only needed fields+ # Local uploads have URLs like "/uploads/..." but NOT protocol-relative "//"+ upload_tuples =+ Upload.where("url NOT LIKE '/%' OR url LIKE '//%'").pluck(+ Arel.sql("COALESCE(NULLIF(original_sha1, ''), sha1)"),+ :id,+ :url,+ :sha1,+ )++ uploads_by_sha1 = {}+ upload_tuples.each do |sha1_key, id, url, sha1|+ uploads_by_sha1[sha1_key] ||= []+ uploads_by_sha1[sha1_key] << UploadData.new(id: id, url: url, sha1: sha1)+ end+ uploads_by_sha1+ end++ def process_upload_group(upload_group)+ primary = upload_group.first+ primary_filename = upload_path_in_archive(primary)++ return if !download_upload_to_file(primary, primary_filename)++ upload_group+ .drop(1)+ .each do |duplicate|+ duplicate_filename = upload_path_in_archive(duplicate)+ hardlink_or_download(primary_filename, duplicate, duplicate_filename)+ end+ end++ def upload_path_in_archive(upload_data)+ path = @s3_store.get_path_for_upload(upload_data)+ File.join(@tmp_directory, @upload_directory, path)+ end++ def download_upload_to_file(upload_data, filename)+ FileUtils.mkdir_p(File.dirname(filename))+ @s3_store.download_file(upload_data, filename)+ increment_and_log_progress(:downloaded)+ true+ rescue StandardError => ex+ log "Failed to download file with upload ID #{upload_data.id} from S3", ex+ false+ end++ def hardlink_or_download(source_filename, upload_data, target_filename)+ FileUtils.mkdir_p(File.dirname(target_filename))+ FileUtils.ln(source_filename, target_filename)+ increment_and_log_progress(:hardlinked)+ rescue StandardError => ex+ log "Failed to create hardlink for upload ID #{upload_data.id}, downloading instead", ex+ download_upload_to_file(upload_data, target_filename)+ end++ def increment_and_log_progress(type)+ @download_stats[type] += 1+ total = @download_stats[:downloaded] + @download_stats[:hardlinked]+ return if total % 1000 != 0++ log "#{total} files processed (#{@download_stats[:downloaded]} downloaded, #{@download_stats[:hardlinked]} hardlinked). Still processing..."enddef upload_archivediff --git a/spec/lib/backup_restore/backuper_spec.rb b/spec/lib/backup_restore/backuper_spec.rbindex 9377ad5c4f2..0d8c195280b 100644--- a/spec/lib/backup_restore/backuper_spec.rb+++ b/spec/lib/backup_restore/backuper_spec.rb@@ -1,6 +1,119 @@# frozen_string_literal: trueRSpec.describe BackupRestore::Backuper do+ describe "#add_remote_uploads_to_archive" do+ fab!(:user)++ let(:backuper) { described_class.new(user.id) }+ let(:tar_filename) { "/tmp/test_backup.tar" }++ before do+ SiteSetting.enable_s3_uploads = true+ SiteSetting.s3_access_key_id = "abc"+ SiteSetting.s3_secret_access_key = "def"+ SiteSetting.s3_upload_bucket = "bucket"+ SiteSetting.include_s3_uploads_in_backups = true++ # Initialize the backuper's tmp directory+ backuper.instance_variable_set(:@tmp_directory, Dir.mktmpdir)+ backuper.instance_variable_set(:@logs, [])+ end++ after { FileUtils.rm_rf(backuper.instance_variable_get(:@tmp_directory)) }++ it "deduplicates uploads with the same original_sha1 using hardlinks" do+ shared_sha1 = SecureRandom.hex(20)++ # Create 3 uploads with the same original_sha1 (simulating secure upload duplicates)+ upload1 =+ Fabricate(+ :upload,+ sha1: SecureRandom.hex(20),+ original_sha1: shared_sha1,+ url: "//bucket.s3.amazonaws.com/original/1X/file1.png",+ )+ upload2 =+ Fabricate(+ :upload,+ sha1: SecureRandom.hex(20),+ original_sha1: shared_sha1,+ url: "//bucket.s3.amazonaws.com/original/2X/file2.png",+ )+ upload3 =+ Fabricate(+ :upload,+ sha1: SecureRandom.hex(20),+ original_sha1: shared_sha1,+ url: "//bucket.s3.amazonaws.com/original/3X/file3.png",+ )++ # Create 1 unique upload+ unique_upload =+ Fabricate(+ :upload,+ sha1: SecureRandom.hex(20),+ original_sha1: SecureRandom.hex(20),+ url: "//bucket.s3.amazonaws.com/original/4X/file4.png",+ )++ store = FileStore::S3Store.new+ download_count = 0++ # Stub get_path_for_upload to extract path from URL (works with UploadData structs)+ store+ .stubs(:get_path_for_upload)+ .with { |obj| obj.url.include?("1X") }+ .returns("original/1X/file1.png")+ store+ .stubs(:get_path_for_upload)+ .with { |obj| obj.url.include?("2X") }+ .returns("original/2X/file2.png")+ store+ .stubs(:get_path_for_upload)+ .with { |obj| obj.url.include?("3X") }+ .returns("original/3X/file3.png")+ store+ .stubs(:get_path_for_upload)+ .with { |obj| obj.url.include?("4X") }+ .returns("original/4X/file4.png")++ store+ .stubs(:download_file)+ .with do |upload_data, filename|+ download_count += 1+ FileUtils.mkdir_p(File.dirname(filename))+ File.write(filename, "file content for #{upload_data.id}")+ true+ end+ .returns(nil)++ FileStore::S3Store.stubs(:new).returns(store)++ Discourse::Utils.stubs(:execute_command)++ silence_stdout { backuper.send(:add_remote_uploads_to_archive, tar_filename) }++ # Should only download 2 files: 1 for the duplicates group + 1 for the unique upload+ expect(download_count).to eq(2)++ # All 4 file paths should exist in the tmp directory+ tmp_dir = backuper.instance_variable_get(:@tmp_directory)+ upload_dir = Discourse.store.upload_path+ expect(File.exist?(File.join(tmp_dir, upload_dir, "original/1X/file1.png"))).to eq(true)+ expect(File.exist?(File.join(tmp_dir, upload_dir, "original/2X/file2.png"))).to eq(true)+ expect(File.exist?(File.join(tmp_dir, upload_dir, "original/3X/file3.png"))).to eq(true)+ expect(File.exist?(File.join(tmp_dir, upload_dir, "original/4X/file4.png"))).to eq(true)++ # The duplicate files should be hardlinks (same inode as the primary)+ file1_stat = File.stat(File.join(tmp_dir, upload_dir, "original/1X/file1.png"))+ file2_stat = File.stat(File.join(tmp_dir, upload_dir, "original/2X/file2.png"))+ file3_stat = File.stat(File.join(tmp_dir, upload_dir, "original/3X/file3.png"))++ expect(file1_stat.ino).to eq(file2_stat.ino)+ expect(file1_stat.ino).to eq(file3_stat.ino)+ end+ end+describe "#get_parameterized_title" doit "returns a non-empty parameterized title when site title contains unicode" doSiteSetting.title = "Ɣ"