Skip to content
Closed
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
14 changes: 14 additions & 0 deletions mooncake-store/include/storage_backend.h
Original file line number Diff line number Diff line change
Expand Up @@ -844,6 +844,14 @@ struct DiskState {

class BucketStorageBackend : public StorageBackendInterface {
public:
enum class MetadataFailurePointForTest {
kNone,
kAfterWrite,
kFileSync,
kRename,
kDirectorySync,
};

BucketStorageBackend(const FileStorageConfig& file_storage_config_,
const BucketBackendConfig& bucket_backend_config_);

Expand Down Expand Up @@ -1265,6 +1273,10 @@ class BucketStorageBackend : public StorageBackendInterface {
// Test-only: inject datasync failure in WriteBucket to verify orphan
// cleanup. SetDatasyncFailureForTest(true) makes WriteBucket fail its
// datasync call and immediately call CleanupOrphanedBucket.
void SetMetadataFailurePointForTest(MetadataFailurePointForTest point) {
test_metadata_failure_point_.store(point, std::memory_order_relaxed);
}

void SetDatasyncFailureForTest(bool enabled) {
test_datasync_failure_.store(enabled, std::memory_order_relaxed);
}
Expand Down Expand Up @@ -1304,6 +1316,8 @@ class BucketStorageBackend : public StorageBackendInterface {
void ReleaseDiskOwnerLocks();

std::atomic<bool> test_datasync_failure_{false};
std::atomic<MetadataFailurePointForTest> test_metadata_failure_point_{
MetadataFailurePointForTest::kNone};
std::atomic<size_t> last_aligned_copy_bytes_{0};
std::atomic<bool> test_direct_io_unavailable_{false};
// Alignment helper functions for O_DIRECT I/O
Expand Down
139 changes: 112 additions & 27 deletions mooncake-store/src/storage_backend.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
#include <cstdlib>
#include <limits>
#include <future>
#include <atomic>

#include <array>
#include <cctype>
Expand Down Expand Up @@ -60,6 +61,7 @@ std::string ErrnoSuffix(int err) {
if (err == 0) return "";
return ", errno=" + std::to_string(err) + " (" + strerror(err) + ")";
}
std::atomic<uint64_t> g_bucket_metadata_temp_sequence{0};
} // namespace

#include "storage/distributed/distributed_storage_backend.h"
Expand Down Expand Up @@ -3246,17 +3248,9 @@ tl::expected<void, ErrorCode> BucketStorageBackend::WriteBucket(
LOG(ERROR) << "Failed to store bucket metadata, error: "
<< store_bucket_metadata_result.error();

// Clean up the bucket file to prevent orphans
std::error_code ec;
if (fs::remove(bucket_data_path, ec)) {
LOG(WARNING) << "Cleaned up orphaned bucket file after metadata "
"write failure: "
<< bucket_data_path;
} else if (ec) {
LOG(ERROR) << "Failed to clean up bucket file after metadata write "
"failure: "
<< bucket_data_path << ", error: " << ec.message();
}
// A rename may succeed before directory sync fails. Clean both
// files so restart cannot recover an unacknowledged partial commit.
CleanupOrphanedBucket(bucket_id, disk_index);

return tl::make_unexpected(ErrorCode::FILE_WRITE_FAIL);
}
Expand Down Expand Up @@ -4172,25 +4166,116 @@ tl::expected<void, ErrorCode> BucketStorageBackend::StoreBucketMetadata(
return tl::make_unexpected(ErrorCode::INTERNAL_ERROR);
}
auto meta_path = meta_path_res.value();
auto open_file_result = OpenFile(meta_path, FileMode::Write);
if (!open_file_result) {
LOG(ERROR) << "Failed to open file for bucket writing: " << meta_path;
std::string str;
try {
struct_pb::to_pb(*metadata, str);
} catch (const std::exception& e) {
LOG(ERROR) << "Failed to serialize bucket metadata for " << meta_path
<< ", error=" << e.what();
return tl::make_unexpected(ErrorCode::FILE_WRITE_FAIL);
}

// Publish metadata through a same-directory temporary file. A direct
// O_TRUNC write can leave a torn .meta file that Init() treats as a bad
// bucket and deletes, even though the bucket data was already synced.
// Bucket IDs are unique; the pid/sequence suffix plus O_EXCL also avoids
// colliding with a stale temporary file after a process restart.
std::string temp_path;
int fd = -1;
for (int attempt = 0; attempt < 128; ++attempt) {
const auto sequence = g_bucket_metadata_temp_sequence.fetch_add(
1, std::memory_order_relaxed);
temp_path = meta_path + ".tmp." + std::to_string(getpid()) + "." +
std::to_string(sequence);
fd = open(temp_path.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC,
0644);
if (fd >= 0 || errno != EEXIST) break;
}
if (fd < 0) {
LOG(ERROR) << "Failed to create temporary bucket metadata file for: "
<< meta_path << ", errno=" << errno << " ("
<< strerror(errno) << ")";
return tl::make_unexpected(ErrorCode::FILE_OPEN_FAIL);
}
auto file = std::move(open_file_result.value());
std::string str;
struct_pb::to_pb(*metadata, str);
auto write_result = file->write(str, str.size());
if (!write_result) {
NotifyDiskError(file->sys_errno(), "write");
LOG(ERROR) << "Write failed for: " << meta_path
<< ", error: " << write_result.error();
return tl::make_unexpected(write_result.error());
FdGuard file_guard(fd);
auto remove_temp = [&]() {
if (unlink(temp_path.c_str()) != 0 && errno != ENOENT) {
LOG(ERROR) << "Failed to remove temporary metadata file "
<< temp_path << ", errno=" << errno << " ("
<< strerror(errno) << ")";
}
};
auto injected_failure = [&](MetadataFailurePointForTest point) {
return test_metadata_failure_point_.load(std::memory_order_relaxed) ==
point;
};

size_t written = 0;
while (written < str.size()) {
const ssize_t result =
write(fd, str.data() + written, str.size() - written);
if (result < 0 && errno == EINTR) continue;
if (result <= 0) {
LOG(ERROR) << "Failed to write temporary bucket metadata: "
<< temp_path << ", errno=" << errno << " ("
<< strerror(errno) << ")";
remove_temp();
return tl::make_unexpected(ErrorCode::FILE_WRITE_FAIL);
}
written += static_cast<size_t>(result);
}
if (injected_failure(MetadataFailurePointForTest::kAfterWrite)) {
remove_temp();
return tl::make_unexpected(ErrorCode::FILE_WRITE_FAIL);
}
if (injected_failure(MetadataFailurePointForTest::kFileSync) ||
fsync(fd) != 0) {
LOG(ERROR) << "Failed to sync temporary bucket metadata: " << temp_path
<< ", errno=" << errno << " (" << strerror(errno) << ")";
remove_temp();
return tl::make_unexpected(ErrorCode::FILE_WRITE_FAIL);
}
if (write_result.value() != str.size()) {
LOG(ERROR) << "Write size mismatch for: " << meta_path
<< ", expected: " << str.size()
<< ", got: " << write_result.value();
if (close(file_guard.release()) != 0) {
LOG(ERROR) << "Failed to close temporary bucket metadata: " << temp_path
<< ", errno=" << errno << " (" << strerror(errno) << ")";
remove_temp();
return tl::make_unexpected(ErrorCode::FILE_WRITE_FAIL);
}

if (injected_failure(MetadataFailurePointForTest::kRename) ||
rename(temp_path.c_str(), meta_path.c_str()) != 0) {
LOG(ERROR) << "Failed to publish bucket metadata " << meta_path
<< ", errno=" << errno << " (" << strerror(errno) << ")";
remove_temp();
return tl::make_unexpected(ErrorCode::FILE_WRITE_FAIL);
}

const auto parent_path =
std::filesystem::path(meta_path).parent_path().empty()
? std::filesystem::path(".")
: std::filesystem::path(meta_path).parent_path();
const int dir_fd =
open(parent_path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (dir_fd < 0) {
LOG(ERROR) << "Failed to open bucket metadata directory " << parent_path
<< ", errno=" << errno << " (" << strerror(errno) << ")";
unlink(meta_path.c_str());
return tl::make_unexpected(ErrorCode::FILE_WRITE_FAIL);
}
FdGuard dir_guard(dir_fd);
if (injected_failure(MetadataFailurePointForTest::kDirectorySync) ||
fsync(dir_fd) != 0) {
LOG(ERROR) << "Failed to sync bucket metadata directory " << parent_path
<< ", errno=" << errno << " (" << strerror(errno) << ")";
if (unlink(meta_path.c_str()) != 0 && errno != ENOENT) {
LOG(ERROR) << "Failed to roll back bucket metadata " << meta_path
<< " after directory sync failure, errno=" << errno
<< " (" << strerror(errno) << ")";
} else if (fsync(dir_fd) != 0) {
LOG(ERROR) << "Failed to sync bucket metadata rollback in "
<< parent_path << ", errno=" << errno << " ("
<< strerror(errno) << ")";
}
return tl::make_unexpected(ErrorCode::FILE_WRITE_FAIL);
}
metadata->meta_size = str.size();
Expand Down
121 changes: 121 additions & 0 deletions mooncake-store/tests/storage_backend_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#include <glog/logging.h>
#include <gtest/gtest.h>
#include <ylt/struct_pb.hpp>

#include <cerrno>
#include <chrono>
Expand Down Expand Up @@ -7622,4 +7623,124 @@ TEST_F(StorageBackendTest, BucketIndexGrowthPreservesRollbackAndRecovery) {
EXPECT_EQ(recovered.GetStoreMetadata()->total_keys, keys_per_bucket);
}

TEST_F(StorageBackendTest, BucketMetadataPublicationFailureDoesNotAcknowledge) {
using Failure = BucketStorageBackend::MetadataFailurePointForTest;
const std::array<Failure, 4> failure_points{
Failure::kAfterWrite, Failure::kFileSync, Failure::kRename,
Failure::kDirectorySync};
FileStorageConfig config;
config.storage_filepath = data_path;
BucketBackendConfig bucket_config;
auto storage_backend =
std::make_unique<BucketStorageBackend>(config, bucket_config);
ASSERT_TRUE(storage_backend->Init());

const std::string key = "metadata_failure_key";
std::string value(65536, 'm');
std::unordered_map<std::string, std::vector<Slice>> batch;
batch.emplace(key, std::vector<Slice>{Slice{value.data(), value.size()}});
int completion_count = 0;
for (const auto failure : failure_points) {
SCOPED_TRACE(static_cast<int>(failure));
storage_backend->SetMetadataFailurePointForTest(failure);
auto result =
storage_backend->BatchOffload(batch, [&](const auto&, auto&) {
++completion_count;
return ErrorCode::OK;
});
ASSERT_FALSE(result.has_value());
EXPECT_EQ(result.error(), ErrorCode::FILE_WRITE_FAIL);
EXPECT_EQ(completion_count, 0);
auto exists = storage_backend->IsExist(key);
ASSERT_TRUE(exists.has_value());
EXPECT_FALSE(exists.value());
for (const auto& entry : fs::directory_iterator(data_path))
EXPECT_EQ(entry.path().filename(), ".mooncake_local_disk.lock");
storage_backend.reset();
{
BucketStorageBackend restarted(config, bucket_config);
ASSERT_TRUE(restarted.Init());
auto recovered = restarted.IsExist(key);
ASSERT_TRUE(recovered.has_value());
EXPECT_FALSE(recovered.value());
}
storage_backend =
std::make_unique<BucketStorageBackend>(config, bucket_config);
ASSERT_TRUE(storage_backend->Init());
}

// Failure must also release the pending write reservation so a retry can
// commit normally, using a new bucket ID rather than a partial metadata.
storage_backend->SetMetadataFailurePointForTest(Failure::kNone);
auto retry = storage_backend->BatchOffload(batch, [&](const auto&, auto&) {
++completion_count;
return ErrorCode::OK;
});
ASSERT_TRUE(retry.has_value());
EXPECT_EQ(completion_count, 1);
storage_backend.reset();
BucketStorageBackend restarted(config, bucket_config);
ASSERT_TRUE(restarted.Init());
auto recovered = restarted.IsExist(key);
ASSERT_TRUE(recovered.has_value());
EXPECT_TRUE(recovered.value());
}

TEST_F(StorageBackendTest, BucketMetadataPublishedBeforeCompletionAndRestart) {
FileStorageConfig config;
config.storage_filepath = data_path;
BucketBackendConfig bucket_config;
std::string value(65536, '\0');
for (size_t i = 0; i < value.size(); ++i) {
value[i] = static_cast<char>(i % 251);
}
const std::string key = "metadata_commit_key";
int completion_count = 0;
{
BucketStorageBackend storage_backend(config, bucket_config);
ASSERT_TRUE(storage_backend.Init());
std::unordered_map<std::string, std::vector<Slice>> batch;
batch.emplace(key,
std::vector<Slice>{Slice{value.data(), value.size()}});
auto result = storage_backend.BatchOffload(
batch, [&](const auto& keys, auto& metadatas) {
++completion_count;
EXPECT_EQ(keys, std::vector<std::string>{key});
EXPECT_EQ(metadatas.size(), 1);
// The completion callback may publish this replica to Master.
// Its files must already be recoverable by an independent
// backend, and temporary metadata must no longer be present.
size_t files = 0;
for (const auto& entry : fs::directory_iterator(data_path)) {
if (entry.path().filename() == ".mooncake_local_disk.lock")
continue;
++files;
EXPECT_TRUE(entry.path().extension() == ".meta" ||
entry.path().extension() == ".bucket");
}
EXPECT_EQ(files, 2);
for (const auto& entry : fs::directory_iterator(data_path)) {
if (entry.path().extension() != ".meta") continue;
std::ifstream input(entry.path(), std::ios::binary);
const std::string bytes(
(std::istreambuf_iterator<char>(input)), {});
BucketMetadata persisted;
EXPECT_NO_THROW(struct_pb::from_pb(persisted, bytes));
EXPECT_EQ(persisted.keys, keys);
}
return ErrorCode::OK;
});
ASSERT_TRUE(result.has_value());
}
EXPECT_EQ(completion_count, 1);

BucketStorageBackend recovered(config, bucket_config);
ASSERT_TRUE(recovered.Init());
std::string loaded(value.size(), '\0');
std::unordered_map<std::string, Slice> reads{
{key, {loaded.data(), loaded.size()}}};
ASSERT_TRUE(recovered.BatchLoad(reads));
EXPECT_EQ(loaded, value);
}

} // namespace mooncake::test
Loading