Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 4 additions & 0 deletions README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)落地前需要显式调大预算。
Expand Down
188 changes: 164 additions & 24 deletions src/core/block_store.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#include <algorithm>
#include <atomic>
#include <chrono>
#include <expected>
#include <fcntl.h>
#include <fstream>
#include <grp.h>
#include <iostream>
Expand Down Expand Up @@ -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<PendingWriteItem> all_write_tasks;
Expand Down Expand Up @@ -324,7 +324,7 @@ namespace ctar
Status write_status;
if (!iovs.empty())
{
write_status = w_file->RandomWriteV(iovs.data(), static_cast<int>(iovs.size()),
write_status = write_file->RandomWriteV(iovs.data(), static_cast<int>(iovs.size()),
file_data_offset_ + batch_start);
}
if (!write_status)
Expand Down Expand Up @@ -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<long>(::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;
Expand All @@ -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<uint64_t> temp_sequence{0};
std::string temp_pack_file;
std::unique_ptr<WriteFile> 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;
Expand Down Expand Up @@ -746,7 +847,7 @@ namespace ctar
available_block_buffers_.push_back(std::make_unique<BlockBuffer>());
}
}
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.
Expand All @@ -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_);
}

Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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)
Expand All @@ -871,7 +972,7 @@ namespace ctar
static_cast<size_t>(stored_metadata_size), stored_metadata);
if (!status)
{
fs::remove(output_pack_file);
cleanup_temp();
return status;
}
}
Expand All @@ -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<off_t>(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 {};
}

Expand Down
6 changes: 5 additions & 1 deletion src/core/block_store.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ namespace ctar
namespace fs = std::filesystem;
using entry_id_t = uint64_t;

class WriteFile;

enum class TaskOperation
{
Pack,
Expand Down Expand Up @@ -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<BlockBuffer> AcquireBlockBuffer();
Expand Down
12 changes: 12 additions & 0 deletions src/core/file_handle.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -499,4 +499,16 @@ namespace ctar
return {std::move(ptr)};
}

ResultStatus<std::unique_ptr<WriteFile>> 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<PosixWriteFile>(file_name, std::move(guard));
return {std::move(ptr)};
}

} // namespace ctar
2 changes: 2 additions & 0 deletions src/core/file_handle.h
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ namespace ctar

ResultStatus<std::unique_ptr<ReadFile>> NewPosixReadFile(const std::string& file_name);
ResultStatus<std::unique_ptr<WriteFile>> NewPosixWriteFile(const std::string& file_name, bool truncate = false);
/// @brief Create a new file exclusively (O_CREAT | O_EXCL); fails if it exists.
ResultStatus<std::unique_ptr<WriteFile>> 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:
Expand Down
Loading
Loading