From df29e8e86e30b5a8b0ef6cfab040fe6b75835500 Mon Sep 17 00:00:00 2001 From: blocksmith314 Date: Sat, 28 Nov 2026 16:39:43 +0800 Subject: [PATCH] fix: pack atomically through a temporary file PackPipeline opened the destination with O_TRUNC before scanning, so a failed pack (for example an empty tree) destroyed an existing archive, and a crash mid-pack left a partial file under the final name. The --force existence check also ignored stat errors and missed broken symlinks. Write to a hidden temporary file created with O_EXCL in the destination directory, rename it into place only after the header, metadata and magic are written and synced, and remove the temporary file on every failure path with error_code cleanup that does not hide the primary error. The existence check now uses symlink_status and reports stat failures. Add AtomicPack tests covering empty-tree failure, mid-pack failure, no-force refusal, successful replacement, and broken symlinks. Closes #77 --- README.md | 5 + README_CN.md | 4 + src/core/block_store.cpp | 188 ++++++++++++++++++++++++++++---- src/core/block_store.h | 6 +- src/core/file_handle.cpp | 12 ++ src/core/file_handle.h | 2 + test/cases/test_block_store.cpp | 137 +++++++++++++++++++++++ 7 files changed, 329 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index dee7592..8cbe714 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,11 @@ ctar ls pack_file.ctar ctar dump pack_file.ctar ``` +`pack` writes to a temporary file in the destination directory and publishes it only after the archive is +complete and synced, so a failed or interrupted pack never leaves a partial archive under the final name. +Without `--force` the final step uses a hard link, so an existing archive is never overwritten; on a +filesystem that cannot create hard links the pack fails and asks for `--force`. + `unpack` limits each file's decompressed size to 1 GiB by default; use `--max-decompressed-size SIZE` to change it (`0` disables the limit). Larger files are rejected until chunked unpacking (#38) lands. diff --git a/README_CN.md b/README_CN.md index 0c0c597..1f94539 100644 --- a/README_CN.md +++ b/README_CN.md @@ -94,6 +94,10 @@ ctar ls pack_file.ctar ctar dump pack_file.ctar ``` +`pack` 先写入目标目录下的临时文件,只有归档完整写入并同步后才发布到最终路径,因此失败或中断 +不会在最终文件名下留下半成品归档。未指定 `--force` 时最后一步使用硬链接,已有归档不会被覆盖; +文件系统不支持硬链接时打包会失败并提示使用 `--force`。 + `unpack` 默认将单个文件的解压大小限制为 1 GiB;可用 `--max-decompressed-size SIZE` 调整(`0` 表示不限制)。超过预算的文件会被拒绝, 在分块支持(#38)落地前需要显式调大预算。 diff --git a/src/core/block_store.cpp b/src/core/block_store.cpp index fbe0d18..082837f 100644 --- a/src/core/block_store.cpp +++ b/src/core/block_store.cpp @@ -1,6 +1,8 @@ #include +#include #include #include +#include #include #include #include @@ -252,16 +254,14 @@ namespace ctar return true; } - void BlockStore::WriterLoop() + void BlockStore::WriterLoop(WriteFile* write_file) { - auto w_res = NewPosixWriteFile(packed_file_); - if (!w_res) + if (write_file == nullptr) { std::unique_lock lock(pack_queue_mutex_); - writer_error_ = w_res.error(); + writer_error_ = error_run_time("writer thread has no output file").error(); return; } - auto& w_file = w_res.value(); while (true) { std::vector all_write_tasks; @@ -324,7 +324,7 @@ namespace ctar Status write_status; if (!iovs.empty()) { - write_status = w_file->RandomWriteV(iovs.data(), static_cast(iovs.size()), + write_status = write_file->RandomWriteV(iovs.data(), static_cast(iovs.size()), file_data_offset_ + batch_start); } if (!write_status) @@ -686,19 +686,91 @@ namespace ctar return {}; } - Status BlockStore::PackPipeline(const std::string& output_pack_file, bool force) + namespace { - std::error_code exists_ec; - if (!force && fs::exists(output_pack_file, exists_ec)) + /// A hidden, unique name in the destination directory. The final rename + /// must stay on the same filesystem to be atomic. + std::string MakeTempPackPath(const std::string& output_file, const uint64_t sequence) + { + const fs::path output_path(output_file); + const std::string file_name = std::format(".{}.tmp.{}.{}", output_path.filename().string(), + static_cast(::getpid()), sequence); + if (output_path.has_parent_path()) + { + return (output_path.parent_path() / file_name).string(); + } + return file_name; + } + + void RemoveTemporaryArchive(const std::string& path) + { + std::error_code ec; + fs::remove(path, ec); + if (ec) + { + std::println(std::cerr, "warning: failed to remove temporary archive '{}': {}", path, ec.message()); + } + } + + /// Removes the temporary archive on scope exit unless released. Keeps the + /// destination directory clean when an exception escapes (thread + /// creation, allocations) after the temporary file was created. + class TempArchiveGuard { - return error_io("output archive '{}' already exists; pass --force to overwrite it", output_pack_file); + public: + explicit TempArchiveGuard(std::string path) : path_(std::move(path)) {} + ~TempArchiveGuard() + { + if (!released_) + { + RemoveTemporaryArchive(path_); + } + } + TempArchiveGuard(const TempArchiveGuard&) = delete; + TempArchiveGuard& operator=(const TempArchiveGuard&) = delete; + void Release() noexcept { released_ = true; } + + private: + std::string path_; + bool released_ = false; + }; + + /// Best-effort fsync of the destination directory so the rename/link + /// survives a crash on filesystems that need it. Failures are ignored: + /// the archive itself is already synced and the name is visible. + void SyncArchiveDirectory(const std::string& output_file) + { + const fs::path parent = fs::path(output_file).parent_path(); + const std::string dir = parent.empty() ? "." : parent.string(); + const int fd = ::open(dir.c_str(), O_RDONLY | O_CLOEXEC); + if (fd < 0) + { + return; + } + (void)::fsync(fd); + (void)::close(fd); } - auto write_file_status = NewPosixWriteFile(output_pack_file, true); - if (!write_file_status) + } // namespace + + Status BlockStore::PackPipeline(const std::string& output_pack_file, bool force) + { + if (!force) { - return error_io("fail to open {}: {} ", output_pack_file, strerror(errno)); + std::error_code exists_ec; + const auto existing = fs::symlink_status(output_pack_file, exists_ec); + if (exists_ec && exists_ec != std::errc::no_such_file_or_directory) + { + return error_io("cannot inspect output archive '{}': {}", output_pack_file, exists_ec.message()); + } + // symlink_status also sees broken symlinks, which fs::exists reports as + // missing; replacing one without --force would be surprising. + if (!exists_ec && existing.type() != fs::file_type::not_found) + { + return error_io("output archive '{}' already exists; pass --force to overwrite it", + output_pack_file); + } } - auto& write_file = write_file_status.value(); + block_region_size_ = 0; max_block_region_size_ = 0; file_data_compressed_size_ = 0; @@ -710,7 +782,36 @@ namespace ctar return status; } - packed_file_ = output_pack_file; + // Pack into a temporary file next to the destination and rename it into + // place only once the archive is complete and synced, so a failure or a + // crash never leaves a partial archive under the final name. + static std::atomic temp_sequence{0}; + std::string temp_pack_file; + std::unique_ptr write_file; + ErrorStatus create_error{}; + for (int attempt = 0; attempt < 16 && !write_file; ++attempt) + { + const std::string candidate = MakeTempPackPath(output_pack_file, temp_sequence.fetch_add(1)); + auto write_file_status = NewPosixWriteFileExclusive(candidate); + if (write_file_status) + { + temp_pack_file = candidate; + write_file = std::move(write_file_status.value()); + } + else + { + create_error = write_file_status.error(); + } + } + if (!write_file) + { + return error_io("fail to create a temporary archive next to '{}': {}", output_pack_file, + create_error.err_message); + } + TempArchiveGuard temp_guard(temp_pack_file); + const auto cleanup_temp = [&temp_pack_file] { RemoveTemporaryArchive(temp_pack_file); }; + + packed_file_ = temp_pack_file; const uint64_t pack_begin_time = CurrentTimeMillis(); const uint64_t raw_meta_size = GetRawMetaSize(); const CompressionType file_data_type = compression_config_.compression_type; @@ -746,7 +847,7 @@ namespace ctar available_block_buffers_.push_back(std::make_unique()); } } - std::thread writer([this] { WriterLoop(); }); + std::thread writer([this, output = write_file.get()] { WriterLoop(output); }); // Will block here until all tasks (pack or unpack, not include the task that write data to disk) complete or // any task fails. @@ -762,12 +863,12 @@ namespace ctar if (!status) { - fs::remove(output_pack_file); + cleanup_temp(); return status; } if (writer_error_) { - fs::remove(output_pack_file); + cleanup_temp(); return std::unexpected(*writer_error_); } @@ -795,7 +896,7 @@ namespace ctar } if (meta_buffer.size() != raw_meta_size) { - fs::remove(output_pack_file); + cleanup_temp(); return error_run_time("internal error: metadata size {} does not match the precomputed {}", meta_buffer.size(), raw_meta_size); } @@ -862,7 +963,7 @@ namespace ctar status = write_file->RandomWrite(0, header_bytes.size(), header_bytes.data()); if (!status) { - fs::remove(output_pack_file); + cleanup_temp(); return status; } if (stored_metadata_size > 0) @@ -871,7 +972,7 @@ namespace ctar static_cast(stored_metadata_size), stored_metadata); if (!status) { - fs::remove(output_pack_file); + cleanup_temp(); return status; } } @@ -881,19 +982,58 @@ namespace ctar sizeof(kMagicNumber), magic_number.data()); if (!status) { - fs::remove(output_pack_file); + cleanup_temp(); return status; } if (!write_file->TruncFile(static_cast(pack_file_size))) { - fs::remove(output_pack_file); + cleanup_temp(); return error_io("fail to truncate compressed file {}: {}", output_pack_file, strerror(errno)); } if (!write_file->Sync()) { - fs::remove(output_pack_file); + cleanup_temp(); return error_io("durable sync failed for archive {}: {}", output_pack_file, strerror(errno)); } + write_file.reset(); + + if (force) + { + std::error_code rename_ec; + fs::rename(temp_pack_file, output_pack_file, rename_ec); + if (rename_ec) + { + cleanup_temp(); + return error_io("fail to move the temporary archive into place '{}': {}", output_pack_file, + rename_ec.message()); + } + } + else + { + // link() is atomic: it fails with EEXIST if the destination appeared + // after the early check, so a concurrent writer is never overwritten. + // Never fall back to rename() here: it would replace that destination + // without --force. + if (::link(temp_pack_file.c_str(), output_pack_file.c_str()) != 0) + { + const int link_errno = errno; + cleanup_temp(); + if (link_errno == EEXIST) + { + return error_io("output archive '{}' already exists; pass --force to overwrite it", + output_pack_file); + } + return error_io( + "cannot publish '{}' without --force: the filesystem refused an atomic no-replace move ({})", + output_pack_file, strerror(link_errno)); + } + // The archive is already reachable under the final name; only the + // temporary link remains to be dropped. + RemoveTemporaryArchive(temp_pack_file); + } + SyncArchiveDirectory(output_pack_file); + temp_guard.Release(); + packed_file_ = output_pack_file; return {}; } diff --git a/src/core/block_store.h b/src/core/block_store.h index 8205d66..856042b 100644 --- a/src/core/block_store.h +++ b/src/core/block_store.h @@ -24,6 +24,8 @@ namespace ctar namespace fs = std::filesystem; using entry_id_t = uint64_t; + class WriteFile; + enum class TaskOperation { Pack, @@ -209,7 +211,9 @@ namespace ctar Status UnPackTask(const DataBlockMeta& block_meta); - void WriterLoop(); + /// @param write_file exclusively opened output; owned by the caller and + /// outlives the writer thread. The writer must not reopen by path. + void WriterLoop(WriteFile* write_file); /// @brief acquire BlockBuffer from available_block_buffers_ std::unique_ptr AcquireBlockBuffer(); diff --git a/src/core/file_handle.cpp b/src/core/file_handle.cpp index 175e0e3..d1c780c 100644 --- a/src/core/file_handle.cpp +++ b/src/core/file_handle.cpp @@ -499,4 +499,16 @@ namespace ctar return {std::move(ptr)}; } + ResultStatus> NewPosixWriteFileExclusive(const std::string& file_name) + { + const int fd = ::open(file_name.c_str(), O_WRONLY | O_CREAT | O_EXCL | kOpenBaseFlags, 0644); + if (fd < 0) + { + return error_io("fail to create file exclusively {}: {}", file_name, strerror(errno)); + } + FdGuard guard(fd); + auto ptr = std::make_unique(file_name, std::move(guard)); + return {std::move(ptr)}; + } + } // namespace ctar diff --git a/src/core/file_handle.h b/src/core/file_handle.h index bd720a2..9687ed5 100644 --- a/src/core/file_handle.h +++ b/src/core/file_handle.h @@ -63,6 +63,8 @@ namespace ctar ResultStatus> NewPosixReadFile(const std::string& file_name); ResultStatus> NewPosixWriteFile(const std::string& file_name, bool truncate = false); + /// @brief Create a new file exclusively (O_CREAT | O_EXCL); fails if it exists. + ResultStatus> NewPosixWriteFileExclusive(const std::string& file_name); // Bounds for a single read/write syscall. The kernel limits how much one call may // carry, and the two platforms react differently when the request is too large: diff --git a/test/cases/test_block_store.cpp b/test/cases/test_block_store.cpp index 84eaa4c..1163d6e 100644 --- a/test/cases/test_block_store.cpp +++ b/test/cases/test_block_store.cpp @@ -1121,6 +1121,143 @@ namespace ctar fixture.Cleanup(); } + namespace + { + struct AtomicPackFixture + { + fs::path root{"atomic_pack_test"}; + fs::path source{root / "source"}; + fs::path empty{root / "empty"}; + fs::path archive{root / "out.ctar"}; + + void Create() + { + fs::remove_all(root); + fs::create_directories(source); + fs::create_directories(empty); + WriteWholeFile((source / "a.txt").string(), "hello"); + + BlockStore store; + ASSERT_TRUE(store.Scan(source.string())); + ASSERT_TRUE(store.PackPipeline(archive.string())); + } + + [[nodiscard]] std::vector TempFiles() const + { + std::vector temps; + for (const auto& entry : fs::directory_iterator(root)) + { + if (entry.path().filename().string().find(".tmp.") != std::string::npos) + { + temps.push_back(entry.path().string()); + } + } + return temps; + } + + void Cleanup() const { fs::remove_all(root); } + }; + } // namespace + + TEST(AtomicPack, FailingPackKeepsExistingArchive) + { + AtomicPackFixture fixture; + fixture.Create(); + const std::string before = ReadWholeFile(fixture.archive.string()); + + // An empty tree fails before any block is written. + BlockStore store; + ASSERT_TRUE(store.Scan(fixture.empty.string())); + const Status status = store.PackPipeline(fixture.archive.string(), true); + ASSERT_FALSE(status); + + EXPECT_EQ(ReadWholeFile(fixture.archive.string()), before); + EXPECT_TRUE(fixture.TempFiles().empty()); + + fixture.Cleanup(); + } + + TEST(AtomicPack, MidPackFailureKeepsExistingArchive) + { + AtomicPackFixture fixture; + fixture.Create(); + const std::string before = ReadWholeFile(fixture.archive.string()); + + // Scan records the file, then it disappears before the pack task reads it. + BlockStore store; + ASSERT_TRUE(store.Scan(fixture.source.string())); + fs::remove(fixture.source / "a.txt"); + const Status status = store.PackPipeline(fixture.archive.string(), true); + ASSERT_FALSE(status); + + EXPECT_EQ(ReadWholeFile(fixture.archive.string()), before); + EXPECT_TRUE(fixture.TempFiles().empty()); + + fixture.Cleanup(); + } + + TEST(AtomicPack, NoForceDoesNotReplaceExistingArchive) + { + AtomicPackFixture fixture; + fixture.Create(); + const std::string before = ReadWholeFile(fixture.archive.string()); + + BlockStore store; + ASSERT_TRUE(store.Scan(fixture.source.string())); + const Status status = store.PackPipeline(fixture.archive.string(), false); + ASSERT_FALSE(status); + + EXPECT_EQ(ReadWholeFile(fixture.archive.string()), before); + EXPECT_TRUE(fixture.TempFiles().empty()); + + fixture.Cleanup(); + } + + TEST(AtomicPack, SuccessfulPackReplacesExistingArchive) + { + AtomicPackFixture fixture; + fixture.Create(); + WriteWholeFile((fixture.source / "a.txt").string(), "replaced"); + + BlockStore store; + ASSERT_TRUE(store.Scan(fixture.source.string())); + ASSERT_TRUE(store.PackPipeline(fixture.archive.string(), true)); + + auto reader = ArchiveReader::Open(fixture.archive.string()); + ASSERT_TRUE(reader) << reader.error().message; + auto data = reader->ReadFile("/a.txt"); + ASSERT_TRUE(data); + EXPECT_EQ(data.value()->view(), "replaced"); + EXPECT_TRUE(fixture.TempFiles().empty()); + + fixture.Cleanup(); + } + + TEST(AtomicPack, BrokenSymlinkRequiresForce) + { + AtomicPackFixture fixture; + fixture.Create(); + fs::remove(fixture.archive); + fs::create_symlink(fixture.root / "missing-target", fixture.archive); + + BlockStore store; + ASSERT_TRUE(store.Scan(fixture.source.string())); + const Status status = store.PackPipeline(fixture.archive.string(), false); + ASSERT_FALSE(status); + EXPECT_TRUE(fs::is_symlink(fixture.archive)); + EXPECT_TRUE(fixture.TempFiles().empty()); + + // --force replaces the symlink itself, not the file it pointed at. + BlockStore forced; + ASSERT_TRUE(forced.Scan(fixture.source.string())); + ASSERT_TRUE(forced.PackPipeline(fixture.archive.string(), true)); + EXPECT_FALSE(fs::is_symlink(fixture.archive)); + EXPECT_FALSE(fs::exists(fixture.root / "missing-target")); + EXPECT_TRUE(fixture.TempFiles().empty()); + + fixture.Cleanup(); + } + namespace { struct UnpackPolicyFixture