You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pegasus.apache.org by la...@apache.org on 2024/01/05 06:45:22 UTC
(incubator-pegasus) branch master updated: refactor(json_file): Refactor the load and dump functions of JSON objects (#1818)
This is an automated email from the ASF dual-hosted git repository.
laiyingchun pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-pegasus.git
The following commit(s) were added to refs/heads/master by this push:
new 14ca78e7e refactor(json_file): Refactor the load and dump functions of JSON objects (#1818)
14ca78e7e is described below
commit 14ca78e7ec3ea3dd70f6f16fc45d89f6b7dfcf5e
Author: Yingchun Lai <la...@apache.org>
AuthorDate: Fri Jan 5 14:45:16 2024 +0800
refactor(json_file): Refactor the load and dump functions of JSON objects (#1818)
This patch mainly refactoring the objects load and dump functions.
There are 2 types of objects, one is using DEFINE_JSON_SERIALIZATION macro to make the object
can be converted to/from JSON string which corresponding to RapidJson, the other is using
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE macro which corresponding to NlohmannJson. So there are 2
types of functions (i.e. load_rjobj_from_file/dump_rjobj_to_file and
load_njobj_from_file/dump_njobj_to_file).
This patch refactor the code to use the newly added functions to do the operations, and also
add some unit tests.
---
src/block_service/local/local_service.cpp | 50 +------
src/block_service/local/local_service.h | 8 +-
src/block_service/test/local_service_test.cpp | 8 +-
src/replica/bulk_load/replica_bulk_loader.cpp | 24 +---
src/replica/bulk_load/replica_bulk_loader.h | 3 +-
.../bulk_load/test/replica_bulk_loader_test.cpp | 25 +---
src/replica/replica_disk_migrator.cpp | 5 +-
src/replica/replica_restore.cpp | 38 +----
src/replica/replication_app_base.cpp | 80 +++--------
src/replica/replication_app_base.h | 58 ++------
src/test/function_test/bulk_load/CMakeLists.txt | 1 +
.../function_test/bulk_load/test_bulk_load.cpp | 34 ++---
src/utils/filesystem.cpp | 2 +-
src/utils/fmt_logging.h | 16 ++-
src/utils/load_dump_object.h | 155 +++++++++++++++++++++
src/utils/test/load_dump_object_test.cpp | 115 +++++++++++++++
16 files changed, 357 insertions(+), 265 deletions(-)
diff --git a/src/block_service/local/local_service.cpp b/src/block_service/local/local_service.cpp
index 9977fbe94..f0dc35f14 100644
--- a/src/block_service/local/local_service.cpp
+++ b/src/block_service/local/local_service.cpp
@@ -16,15 +16,14 @@
// under the License.
#include <rocksdb/env.h>
-#include <initializer_list>
#include <memory>
#include <set>
#include <type_traits>
#include <utility>
+#include "absl/strings/string_view.h"
#include "local_service.h"
#include "nlohmann/json.hpp"
-#include "nlohmann/json_fwd.hpp"
#include "rocksdb/slice.h"
#include "rocksdb/status.h"
#include "runtime/task/async_calls.h"
@@ -36,7 +35,7 @@
#include "utils/filesystem.h"
#include "utils/flags.h"
#include "utils/fmt_logging.h"
-#include "absl/strings/string_view.h"
+#include "utils/load_dump_object.h"
#include "utils/strings.h"
DSN_DECLARE_bool(enable_direct_io);
@@ -53,41 +52,6 @@ namespace block_service {
DEFINE_TASK_CODE(LPC_LOCAL_SERVICE_CALL, TASK_PRIORITY_COMMON, THREAD_POOL_BLOCK_SERVICE)
-error_code file_metadata::dump_to_file(const std::string &file_path) const
-{
- std::string data = nlohmann::json(*this).dump();
- auto s =
- rocksdb::WriteStringToFile(dsn::utils::PegasusEnv(dsn::utils::FileDataType::kSensitive),
- rocksdb::Slice(data),
- file_path,
- /* should_sync */ true);
- if (!s.ok()) {
- LOG_WARNING("write to metadata file '{}' failed, err = {}", file_path, s.ToString());
- return ERR_FS_INTERNAL;
- }
-
- return ERR_OK;
-}
-
-error_code file_metadata::load_from_file(const std::string &file_path)
-{
- std::string data;
- auto s = rocksdb::ReadFileToString(
- dsn::utils::PegasusEnv(dsn::utils::FileDataType::kSensitive), file_path, &data);
- if (!s.ok()) {
- LOG_WARNING("load from metadata file '{}' failed, err = {}", file_path, s.ToString());
- return ERR_FS_INTERNAL;
- }
-
- try {
- nlohmann::json::parse(data).get_to(*this);
- return ERR_OK;
- } catch (nlohmann::json::exception &exp) {
- LOG_WARNING("decode metadata from json failed: {}, data = [{}]", exp.what(), data);
- return ERR_FS_INTERNAL;
- }
-}
-
std::string local_service::get_metafile(const std::string &filepath)
{
std::string dir_part = utils::filesystem::remove_file_name(filepath);
@@ -294,7 +258,7 @@ error_code local_file_object::load_metadata()
file_metadata fmd;
std::string filepath = local_service::get_metafile(file_name());
- auto ec = fmd.load_from_file(filepath);
+ auto ec = dsn::utils::load_njobj_from_file(filepath, &fmd);
if (ec != ERR_OK) {
LOG_WARNING("load metadata file '{}' failed", filepath);
return ERR_FS_INTERNAL;
@@ -356,8 +320,8 @@ dsn::task_ptr local_file_object::write(const write_request &req,
// a lot, but it is somewhat not correct.
_size = resp.written_size;
_md5_value = utils::string_md5(req.buffer.data(), req.buffer.length());
- auto err = file_metadata(_size, _md5_value)
- .dump_to_file(local_service::get_metafile(file_name()));
+ auto err = dsn::utils::dump_njobj_to_file(file_metadata(_size, _md5_value),
+ local_service::get_metafile(file_name()));
if (err != ERR_OK) {
LOG_ERROR("file_metadata write failed");
resp.err = ERR_FS_INTERNAL;
@@ -498,8 +462,8 @@ dsn::task_ptr local_file_object::upload(const upload_request &req,
break;
}
- auto err = file_metadata(_size, _md5_value)
- .dump_to_file(local_service::get_metafile(file_name()));
+ auto err = dsn::utils::dump_njobj_to_file(file_metadata(_size, _md5_value),
+ local_service::get_metafile(file_name()));
if (err != ERR_OK) {
LOG_ERROR("file_metadata write failed");
resp.err = ERR_FS_INTERNAL;
diff --git a/src/block_service/local/local_service.h b/src/block_service/local/local_service.h
index 0c1a5ee88..c67b9913e 100644
--- a/src/block_service/local/local_service.h
+++ b/src/block_service/local/local_service.h
@@ -41,14 +41,8 @@ struct file_metadata
std::string md5;
file_metadata(int64_t s = 0, const std::string &m = "") : size(s), md5(m) {}
-
- // Dump the object to a file in JSON format.
- error_code dump_to_file(const std::string &file_path) const;
-
- // Load the object from a file in JSON format.
- error_code load_from_file(const std::string &file_path);
};
-NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(file_metadata, size, md5)
+NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(file_metadata, size, md5);
class local_service : public block_filesystem
{
diff --git a/src/block_service/test/local_service_test.cpp b/src/block_service/test/local_service_test.cpp
index 5eeb8dd0f..9cbb7eeda 100644
--- a/src/block_service/test/local_service_test.cpp
+++ b/src/block_service/test/local_service_test.cpp
@@ -32,6 +32,7 @@
#include "test_util/test_util.h"
#include "utils/env.h"
#include "utils/error_code.h"
+#include "utils/load_dump_object.h"
namespace dsn {
namespace dist {
@@ -49,11 +50,11 @@ TEST_P(local_service_test, file_metadata)
const int64_t kSize = 12345;
const std::string kMD5 = "0123456789abcdef0123456789abcdef";
auto meta_file_path = local_service::get_metafile("a.txt");
- ASSERT_EQ(ERR_OK, file_metadata(kSize, kMD5).dump_to_file(meta_file_path));
+ ASSERT_EQ(ERR_OK, dsn::utils::dump_njobj_to_file(file_metadata(kSize, kMD5), meta_file_path));
ASSERT_TRUE(boost::filesystem::exists(meta_file_path));
file_metadata fm;
- fm.load_from_file(meta_file_path);
+ ASSERT_EQ(ERR_OK, dsn::utils::load_njobj_from_file(meta_file_path, &fm));
ASSERT_EQ(kSize, fm.size);
ASSERT_EQ(kMD5, fm.md5);
}
@@ -64,7 +65,8 @@ TEST_P(local_service_test, load_metadata)
auto meta_file_path = local_service::get_metafile(file.file_name());
{
- ASSERT_EQ(ERR_OK, file_metadata(5, "abcde").dump_to_file(meta_file_path));
+ ASSERT_EQ(ERR_OK,
+ dsn::utils::dump_njobj_to_file(file_metadata(5, "abcde"), meta_file_path));
ASSERT_EQ(ERR_OK, file.load_metadata());
ASSERT_EQ("abcde", file.get_md5sum());
ASSERT_EQ(5, file.get_size());
diff --git a/src/replica/bulk_load/replica_bulk_loader.cpp b/src/replica/bulk_load/replica_bulk_loader.cpp
index 6672fdceb..b92a98885 100644
--- a/src/replica/bulk_load/replica_bulk_loader.cpp
+++ b/src/replica/bulk_load/replica_bulk_loader.cpp
@@ -16,18 +16,16 @@
// under the License.
#include <fmt/core.h>
-#include <rocksdb/env.h>
-#include <rocksdb/status.h>
#include <functional>
#include <memory>
#include <unordered_map>
#include <utility>
#include <vector>
+#include "absl/strings/string_view.h"
#include "block_service/block_service_manager.h"
#include "common/bulk_load_common.h"
#include "common/gpid.h"
-#include "common/json_helper.h"
#include "common/replication.codes.h"
#include "common/replication_common.h"
#include "common/replication_enums.h"
@@ -42,14 +40,12 @@
#include "runtime/rpc/rpc_holder.h"
#include "runtime/task/async_calls.h"
#include "utils/autoref_ptr.h"
-#include "utils/blob.h"
#include "utils/chrono_literals.h"
#include "utils/env.h"
#include "utils/fail_point.h"
#include "utils/filesystem.h"
#include "utils/fmt_logging.h"
-#include "utils/ports.h"
-#include "absl/strings/string_view.h"
+#include "utils/load_dump_object.h"
#include "utils/thread_access_checker.h"
METRIC_DEFINE_counter(replica,
@@ -606,18 +602,10 @@ void replica_bulk_loader::download_sst_file(const std::string &remote_dir,
// need to acquire write lock while calling it
error_code replica_bulk_loader::parse_bulk_load_metadata(const std::string &fname)
{
- std::string buf;
- auto s = rocksdb::ReadFileToString(
- dsn::utils::PegasusEnv(dsn::utils::FileDataType::kSensitive), fname, &buf);
- if (dsn_unlikely(!s.ok())) {
- LOG_ERROR_PREFIX("read file {} failed, error = {}", fname, s.ToString());
- return ERR_FILE_OPERATION_FAILED;
- }
-
- blob bb = blob::create_from_bytes(std::move(buf));
- if (!json::json_forwarder<bulk_load_metadata>::decode(bb, _metadata)) {
- LOG_ERROR_PREFIX("file({}) is damaged", fname);
- return ERR_CORRUPTION;
+ auto ec = dsn::utils::load_rjobj_from_file(fname, &_metadata);
+ if (ec != ERR_OK) {
+ LOG_ERROR_PREFIX("load bulk_load_metadata from file {} failed", fname);
+ return ec;
}
if (_metadata.file_total_size <= 0) {
diff --git a/src/replica/bulk_load/replica_bulk_loader.h b/src/replica/bulk_load/replica_bulk_loader.h
index fcfcca589..5559f6d4a 100644
--- a/src/replica/bulk_load/replica_bulk_loader.h
+++ b/src/replica/bulk_load/replica_bulk_loader.h
@@ -92,7 +92,8 @@ private:
int32_t file_index,
dist::block_service::block_filesystem *fs);
- // \return ERR_FILE_OPERATION_FAILED: file not exist, get size failed, open file failed
+ // \return ERR_PATH_NOT_FOUND: file not exist
+ // \return ERR_FILE_OPERATION_FAILED: get size failed, open file failed
// \return ERR_CORRUPTION: parse failed
// need to acquire write lock while calling it
error_code parse_bulk_load_metadata(const std::string &fname);
diff --git a/src/replica/bulk_load/test/replica_bulk_loader_test.cpp b/src/replica/bulk_load/test/replica_bulk_loader_test.cpp
index 59a00cd28..bb874d500 100644
--- a/src/replica/bulk_load/test/replica_bulk_loader_test.cpp
+++ b/src/replica/bulk_load/test/replica_bulk_loader_test.cpp
@@ -17,17 +17,12 @@
#include "replica/bulk_load/replica_bulk_loader.h"
-#include <fmt/core.h>
-#include <rocksdb/env.h>
-#include <rocksdb/slice.h>
-#include <rocksdb/status.h>
#include <fstream> // IWYU pragma: keep
#include <memory>
#include <vector>
#include "common/bulk_load_common.h"
#include "common/gpid.h"
-#include "common/json_helper.h"
#include "dsn.layer2_types.h"
#include "gtest/gtest.h"
#include "replica/test/mock_utils.h"
@@ -35,10 +30,9 @@
#include "runtime/rpc/rpc_address.h"
#include "runtime/task/task_tracker.h"
#include "test_util/test_util.h"
-#include "utils/blob.h"
-#include "utils/env.h"
#include "utils/fail_point.h"
#include "utils/filesystem.h"
+#include "utils/load_dump_object.h"
#include "utils/test_macros.h"
namespace dsn {
@@ -258,14 +252,7 @@ public:
_metadata.files.emplace_back(_file_meta);
_metadata.file_total_size = _file_meta.size;
std::string whole_name = utils::filesystem::path_combine(LOCAL_DIR, METADATA);
- blob bb = json::json_forwarder<bulk_load_metadata>::encode(_metadata);
- auto s =
- rocksdb::WriteStringToFile(dsn::utils::PegasusEnv(dsn::utils::FileDataType::kSensitive),
- rocksdb::Slice(bb.data(), bb.length()),
- whole_name,
- /* should_sync */ true);
- ASSERT_TRUE(s.ok()) << fmt::format(
- "write file {} failed, err = {}", whole_name, s.ToString());
+ ASSERT_EQ(ERR_OK, utils::dump_rjobj_to_file(_metadata, whole_name));
}
bool validate_metadata()
@@ -525,7 +512,7 @@ TEST_P(replica_bulk_loader_test, rollback_to_downloading_test)
// parse_bulk_load_metadata unit tests
TEST_P(replica_bulk_loader_test, bulk_load_metadata_not_exist)
{
- ASSERT_EQ(test_parse_bulk_load_metadata("path_not_exist"), ERR_FILE_OPERATION_FAILED);
+ ASSERT_EQ(ERR_PATH_NOT_FOUND, test_parse_bulk_load_metadata("path_not_exist"));
}
TEST_P(replica_bulk_loader_test, bulk_load_metadata_corrupt)
@@ -535,8 +522,7 @@ TEST_P(replica_bulk_loader_test, bulk_load_metadata_corrupt)
NO_FATALS(pegasus::create_local_test_file(utils::filesystem::path_combine(LOCAL_DIR, METADATA),
&_file_meta));
std::string metadata_file_name = utils::filesystem::path_combine(LOCAL_DIR, METADATA);
- error_code ec = test_parse_bulk_load_metadata(metadata_file_name);
- ASSERT_EQ(ERR_CORRUPTION, ec);
+ ASSERT_EQ(ERR_CORRUPTION, test_parse_bulk_load_metadata(metadata_file_name));
utils::filesystem::remove_path(LOCAL_DIR);
}
@@ -546,8 +532,7 @@ TEST_P(replica_bulk_loader_test, bulk_load_metadata_parse_succeed)
NO_FATALS(create_local_metadata_file());
std::string metadata_file_name = utils::filesystem::path_combine(LOCAL_DIR, METADATA);
- auto ec = test_parse_bulk_load_metadata(metadata_file_name);
- ASSERT_EQ(ec, ERR_OK);
+ ASSERT_EQ(ERR_OK, test_parse_bulk_load_metadata(metadata_file_name));
ASSERT_TRUE(validate_metadata());
utils::filesystem::remove_path(LOCAL_DIR);
}
diff --git a/src/replica/replica_disk_migrator.cpp b/src/replica/replica_disk_migrator.cpp
index 355421503..4ad9cb98c 100644
--- a/src/replica/replica_disk_migrator.cpp
+++ b/src/replica/replica_disk_migrator.cpp
@@ -36,6 +36,7 @@
#include "utils/filesystem.h"
#include "utils/fmt_logging.h"
#include "utils/thread_access_checker.h"
+#include "utils/load_dump_object.h"
namespace dsn {
namespace replication {
@@ -251,7 +252,9 @@ bool replica_disk_migrator::migrate_replica_app_info(const replica_disk_migrate_
return false;
});
replica_init_info init_info = _replica->get_app()->init_info();
- const auto &store_init_info_err = init_info.store(_target_replica_dir);
+ const auto &store_init_info_err = utils::dump_rjobj_to_file(
+ init_info,
+ utils::filesystem::path_combine(_target_replica_dir, replica_init_info::kInitInfo));
if (store_init_info_err != ERR_OK) {
LOG_ERROR_PREFIX("disk migration(origin={}, target={}) stores app init info failed({})",
req.origin_disk,
diff --git a/src/replica/replica_restore.cpp b/src/replica/replica_restore.cpp
index 9c255df0b..47ef20d2b 100644
--- a/src/replica/replica_restore.cpp
+++ b/src/replica/replica_restore.cpp
@@ -17,8 +17,6 @@
#include <boost/cstdint.hpp>
#include <boost/lexical_cast.hpp>
-#include <rocksdb/env.h>
-#include <rocksdb/status.h>
#include <stdint.h>
#include <atomic>
#include <fstream>
@@ -34,7 +32,6 @@
#include "block_service/block_service_manager.h"
#include "common/backup_common.h"
#include "common/gpid.h"
-#include "common/json_helper.h"
#include "common/replication.codes.h"
#include "dsn.layer2_types.h"
#include "failure_detector/failure_detector_multimaster.h"
@@ -55,6 +52,7 @@
#include "utils/error_code.h"
#include "utils/filesystem.h"
#include "utils/fmt_logging.h"
+#include "utils/load_dump_object.h"
using namespace dsn::dist::block_service;
@@ -95,31 +93,6 @@ bool replica::remove_useless_file_under_chkpt(const std::string &chkpt_dir,
return true;
}
-bool replica::read_cold_backup_metadata(const std::string &fname,
- cold_backup_metadata &backup_metadata)
-{
- if (!::dsn::utils::filesystem::file_exists(fname)) {
- LOG_ERROR_PREFIX(
- "checkpoint on remote storage media is damaged, coz file({}) doesn't exist", fname);
- return false;
- }
-
- std::string data;
- auto s = rocksdb::ReadFileToString(
- dsn::utils::PegasusEnv(dsn::utils::FileDataType::kSensitive), fname, &data);
- if (!s.ok()) {
- LOG_ERROR_PREFIX("read file '{}' failed, err = {}", fname, s.ToString());
- return false;
- }
-
- if (!::dsn::json::json_forwarder<cold_backup_metadata>::decode(
- blob::create_from_bytes(std::move(data)), backup_metadata)) {
- LOG_ERROR_PREFIX("file({}) under checkpoint is damaged", fname);
- return false;
- }
- return true;
-}
-
error_code replica::download_checkpoint(const configuration_restore_request &req,
const std::string &remote_chkpt_dir,
const std::string &local_chkpt_dir)
@@ -206,13 +179,14 @@ error_code replica::get_backup_metadata(block_filesystem *fs,
return err;
}
- // parse cold_backup_meta from metadata file
+ // Load cold_backup_metadata from metadata file.
const std::string local_backup_metada_file =
utils::filesystem::path_combine(local_chkpt_dir, cold_backup_constant::BACKUP_METADATA);
- if (!read_cold_backup_metadata(local_backup_metada_file, backup_metadata)) {
- LOG_ERROR_PREFIX("read cold_backup_metadata from file({}) failed",
+ auto ec = dsn::utils::load_rjobj_from_file(local_backup_metada_file, &backup_metadata);
+ if (ec != ERR_OK) {
+ LOG_ERROR_PREFIX("load cold_backup_metadata from file({}) failed",
local_backup_metada_file);
- return ERR_FILE_OPERATION_FAILED;
+ return ec;
}
_chkpt_total_size = backup_metadata.checkpoint_total_size;
diff --git a/src/replica/replication_app_base.cpp b/src/replica/replication_app_base.cpp
index 9e3f984cb..bc25925d1 100644
--- a/src/replica/replication_app_base.cpp
+++ b/src/replica/replication_app_base.cpp
@@ -25,9 +25,9 @@
*/
#include <alloca.h>
+#include <fmt/core.h>
#include <rocksdb/env.h>
#include <rocksdb/status.h>
-#include <fstream>
#include <memory>
#include <utility>
#include <vector>
@@ -43,7 +43,6 @@
#include "mutation.h"
#include "replica.h"
#include "replica/replication_app_base.h"
-#include "runtime/api_layer1.h"
#include "runtime/rpc/rpc_message.h"
#include "runtime/rpc/serialization.h"
#include "runtime/task/task_code.h"
@@ -52,10 +51,13 @@
#include "utils/binary_reader.h"
#include "utils/binary_writer.h"
#include "utils/blob.h"
+#include "utils/env.h"
#include "utils/factory_store.h"
#include "utils/fail_point.h"
+#include "utils/filesystem.h"
#include "utils/fmt_logging.h"
#include "utils/latency_tracer.h"
+#include "utils/load_dump_object.h"
METRIC_DEFINE_counter(replica,
committed_requests,
@@ -68,65 +70,13 @@ namespace replication {
const std::string replica_init_info::kInitInfo = ".init-info";
-error_code replica_init_info::load(const std::string &dir)
-{
- std::string info_path = utils::filesystem::path_combine(dir, kInitInfo);
- LOG_AND_RETURN_NOT_TRUE(ERROR,
- utils::filesystem::path_exists(info_path),
- ERR_PATH_NOT_FOUND,
- "file({}) not exist",
- info_path);
- LOG_AND_RETURN_NOT_OK(
- ERROR, load_json(info_path), "load replica_init_info from {} failed", info_path);
- LOG_INFO("load replica_init_info from {} succeed: {}", info_path, to_string());
- return ERR_OK;
-}
-
-error_code replica_init_info::store(const std::string &dir)
-{
- uint64_t start = dsn_now_ns();
- std::string info_path = utils::filesystem::path_combine(dir, kInitInfo);
- LOG_AND_RETURN_NOT_OK(ERROR,
- store_json(info_path),
- "store replica_init_info to {} failed, time_used_ns = {}",
- info_path,
- dsn_now_ns() - start);
- LOG_INFO("store replica_init_info to {} succeed, time_used_ns = {}: {}",
- info_path,
- dsn_now_ns() - start,
- to_string());
- return ERR_OK;
-}
-
-error_code replica_init_info::load_json(const std::string &fname)
-{
- std::string data;
- auto s = rocksdb::ReadFileToString(
- dsn::utils::PegasusEnv(dsn::utils::FileDataType::kSensitive), fname, &data);
- LOG_AND_RETURN_NOT_TRUE(ERROR, s.ok(), ERR_FILE_OPERATION_FAILED, "read file {} failed", fname);
- LOG_AND_RETURN_NOT_TRUE(ERROR,
- json::json_forwarder<replica_init_info>::decode(
- blob::create_from_bytes(std::move(data)), *this),
- ERR_FILE_OPERATION_FAILED,
- "decode json from file {} failed",
- fname);
- return ERR_OK;
-}
-
-error_code replica_init_info::store_json(const std::string &fname)
-{
- return write_blob_to_file(fname,
- json::json_forwarder<replica_init_info>::encode(*this),
- dsn::utils::FileDataType::kSensitive);
-}
-
std::string replica_init_info::to_string()
{
- // TODO(yingchun): use fmt instead
- std::ostringstream oss;
- oss << "init_ballot = " << init_ballot << ", init_durable_decree = " << init_durable_decree
- << ", init_offset_in_private_log = " << init_offset_in_private_log;
- return oss.str();
+ return fmt::format(
+ "init_ballot = {}, init_durable_decree = {}, init_offset_in_private_log = {}",
+ init_ballot,
+ init_durable_decree,
+ init_offset_in_private_log);
}
error_code replica_app_info::load(const std::string &fname)
@@ -164,7 +114,8 @@ error_code replica_app_info::store(const std::string &fname)
marshall(writer, tmp, DSF_THRIFT_JSON);
}
- return write_blob_to_file(fname, writer.get_buffer(), dsn::utils::FileDataType::kSensitive);
+ return dsn::utils::write_data_to_file(
+ fname, writer.get_buffer(), dsn::utils::FileDataType::kSensitive);
}
/*static*/
@@ -223,7 +174,8 @@ error_code replication_app_base::open_internal(replica *r)
_last_committed_decree = last_durable_decree();
- auto err = _info.load(r->dir());
+ auto err = dsn::utils::load_rjobj_from_file(
+ utils::filesystem::path_combine(r->dir(), replica_init_info::kInitInfo), &_info);
LOG_AND_RETURN_NOT_OK(ERROR_PREFIX, err, "load replica_init_info failed");
LOG_AND_RETURN_NOT_TRUE(ERROR_PREFIX,
@@ -435,7 +387,11 @@ error_code replication_app_base::update_init_info(replica *r,
_info.init_durable_decree = durable_decree;
_info.init_offset_in_private_log = private_log_offset;
- LOG_AND_RETURN_NOT_OK(ERROR_PREFIX, _info.store(r->dir()), "store replica_init_info failed");
+ LOG_AND_RETURN_NOT_OK(
+ ERROR_PREFIX,
+ utils::dump_rjobj_to_file(
+ _info, utils::filesystem::path_combine(r->dir(), replica_init_info::kInitInfo)),
+ "store replica_init_info failed");
return ERR_OK;
}
diff --git a/src/replica/replication_app_base.h b/src/replica/replication_app_base.h
index db3f44c1c..b8014003e 100644
--- a/src/replica/replication_app_base.h
+++ b/src/replica/replication_app_base.h
@@ -26,12 +26,8 @@
#pragma once
-#include <rocksdb/env.h>
-#include <rocksdb/slice.h>
-#include <rocksdb/status.h>
-#include <stdint.h>
-#include <string.h>
#include <atomic>
+#include <cstdint>
#include <map>
#include <string>
@@ -41,11 +37,7 @@
#include "metadata_types.h"
#include "replica/replica_base.h"
#include "replica_admin_types.h"
-#include "utils/defer.h"
-#include "utils/env.h"
#include "utils/error_code.h"
-#include "utils/filesystem.h"
-#include "utils/fmt_logging.h"
#include "utils/fmt_utils.h"
#include "utils/metrics.h"
#include "utils/ports.h"
@@ -56,46 +48,21 @@ class blob;
class message_ex;
namespace replication {
-
class learn_state;
class mutation;
class replica;
-namespace {
-template <class T>
-error_code write_blob_to_file(const std::string &fname,
- const T &data,
- const dsn::utils::FileDataType &fileDataType)
-{
- std::string tmp_fname = fname + ".tmp";
- auto cleanup = defer([tmp_fname]() { utils::filesystem::remove_path(tmp_fname); });
- auto s = rocksdb::WriteStringToFile(dsn::utils::PegasusEnv(fileDataType),
- rocksdb::Slice(data.data(), data.length()),
- tmp_fname,
- /* should_sync */ true);
- LOG_AND_RETURN_NOT_TRUE(
- ERROR, s.ok(), ERR_FILE_OPERATION_FAILED, "write file {} failed", tmp_fname);
- LOG_AND_RETURN_NOT_TRUE(ERROR,
- utils::filesystem::rename_path(tmp_fname, fname),
- ERR_FILE_OPERATION_FAILED,
- "move file from {} to {} failed",
- tmp_fname,
- fname);
- return ERR_OK;
-}
-} // namespace
-
class replica_init_info
{
public:
- int32_t magic;
- int32_t crc;
- ballot init_ballot;
- decree init_durable_decree;
- int64_t init_offset_in_shared_log; // Deprecated since Pegasus 2.6.0, but leave it to keep
- // compatible readability to read replica_init_info from
- // older Pegasus version.
- int64_t init_offset_in_private_log;
+ int32_t magic = 0;
+ int32_t crc = 0;
+ ballot init_ballot = 0;
+ decree init_durable_decree = 0;
+ int64_t init_offset_in_shared_log = 0; // Deprecated since Pegasus 2.6.0, but leave it to keep
+ // compatible readability to read replica_init_info from
+ // older Pegasus version.
+ int64_t init_offset_in_private_log = 0;
DEFINE_JSON_SERIALIZATION(init_ballot,
init_durable_decree,
init_offset_in_shared_log,
@@ -104,14 +71,7 @@ public:
static const std::string kInitInfo;
public:
- replica_init_info() { memset((void *)this, 0, sizeof(*this)); }
- error_code load(const std::string &dir) WARN_UNUSED_RESULT;
- error_code store(const std::string &dir);
std::string to_string();
-
-private:
- error_code load_json(const std::string &fname);
- error_code store_json(const std::string &fname);
};
class replica_app_info
diff --git a/src/test/function_test/bulk_load/CMakeLists.txt b/src/test/function_test/bulk_load/CMakeLists.txt
index ae1fd559b..03f55fac2 100644
--- a/src/test/function_test/bulk_load/CMakeLists.txt
+++ b/src/test/function_test/bulk_load/CMakeLists.txt
@@ -39,6 +39,7 @@ set(MY_PROJ_LIBS
krb5
function_test_utils
test_utils
+ dsn_utils
rocksdb
lz4
zstd
diff --git a/src/test/function_test/bulk_load/test_bulk_load.cpp b/src/test/function_test/bulk_load/test_bulk_load.cpp
index 502553f03..85db39c7b 100644
--- a/src/test/function_test/bulk_load/test_bulk_load.cpp
+++ b/src/test/function_test/bulk_load/test_bulk_load.cpp
@@ -39,7 +39,6 @@
#include "client/partition_resolver.h"
#include "client/replication_ddl_client.h"
#include "common/bulk_load_common.h"
-#include "common/json_helper.h"
#include "gtest/gtest.h"
#include "include/pegasus/client.h" // IWYU pragma: keep
#include "meta/meta_bulk_load_service.h"
@@ -52,6 +51,7 @@
#include "utils/errors.h"
#include "utils/filesystem.h"
#include "utils/flags.h"
+#include "utils/load_dump_object.h"
#include "utils/test_macros.h"
#include "utils/utils.h"
@@ -89,18 +89,6 @@ protected:
NO_FATALS(run_cmd_from_project_root("rm -rf " + bulk_load_local_app_root_));
}
- // Generate the 'bulk_load_info' file according to 'bli' to path 'bulk_load_info_path'.
- void generate_bulk_load_info(const bulk_load_info &bli, const std::string &bulk_load_info_path)
- {
- auto value = dsn::json::json_forwarder<bulk_load_info>::encode(bli);
- auto s =
- rocksdb::WriteStringToFile(dsn::utils::PegasusEnv(dsn::utils::FileDataType::kSensitive),
- rocksdb::Slice(value.data(), value.length()),
- bulk_load_info_path,
- /* should_sync */ true);
- ASSERT_TRUE(s.ok()) << s.ToString();
- }
-
// Generate the '.xxx.meta' file according to the 'xxx' file
// in path 'file_path'.
void generate_metadata_file(const std::string &file_path)
@@ -110,7 +98,7 @@ protected:
file_path, dsn::utils::FileDataType::kSensitive, fm.size));
ASSERT_EQ(ERR_OK, dsn::utils::filesystem::md5sum(file_path, fm.md5));
auto metadata_file_path = dist::block_service::local_service::get_metafile(file_path);
- ASSERT_EQ(ERR_OK, fm.dump_to_file(metadata_file_path));
+ ASSERT_EQ(ERR_OK, dsn::utils::dump_njobj_to_file(fm, metadata_file_path));
}
void generate_bulk_load_files()
@@ -192,15 +180,9 @@ protected:
}
// Generate 'bulk_load_metadata' file for each partition.
- blob bb = json::json_forwarder<bulk_load_metadata>::encode(blm);
std::string blm_path = dsn::utils::filesystem::path_combine(
partition_path, bulk_load_constant::BULK_LOAD_METADATA);
- auto s = rocksdb::WriteStringToFile(
- dsn::utils::PegasusEnv(dsn::utils::FileDataType::kSensitive),
- rocksdb::Slice(bb.data(), bb.length()),
- blm_path,
- /* should_sync */ true);
- ASSERT_TRUE(s.ok()) << s.ToString();
+ ASSERT_EQ(ERR_OK, dsn::utils::dump_rjobj_to_file(blm, blm_path));
// Generate '.bulk_load_metadata.meta' file of 'bulk_load_metadata'.
NO_FATALS(generate_metadata_file(blm_path));
@@ -208,8 +190,10 @@ protected:
// Generate 'bulk_load_info' file for this table.
auto bulk_load_info_path = fmt::format("{}/bulk_load_info", bulk_load_local_app_root_);
- NO_FATALS(generate_bulk_load_info(bulk_load_info(table_id_, table_name_, partition_count_),
- bulk_load_info_path));
+ ASSERT_EQ(
+ ERR_OK,
+ dsn::utils::dump_rjobj_to_file(bulk_load_info(table_id_, table_name_, partition_count_),
+ bulk_load_info_path));
// Generate '.bulk_load_info.meta' file of 'bulk_load_info'.
NO_FATALS(generate_metadata_file(bulk_load_info_path));
@@ -334,10 +318,10 @@ TEST_F(bulk_load_test, inconsistent_bulk_load_info)
// kind of inconsistencies.
bulk_load_info tests[] = {{table_id_ + 1, table_name_, partition_count_},
{table_id_, table_name_, partition_count_ * 2}};
+ auto bulk_load_info_path = fmt::format("{}/bulk_load_info", bulk_load_local_app_root_);
for (const auto &test : tests) {
// Generate inconsistent 'bulk_load_info'.
- auto bulk_load_info_path = fmt::format("{}/bulk_load_info", bulk_load_local_app_root_);
- NO_FATALS(generate_bulk_load_info(test, bulk_load_info_path));
+ ASSERT_EQ(ERR_OK, dsn::utils::dump_rjobj_to_file(test, bulk_load_info_path));
// Generate '.bulk_load_info.meta'.
NO_FATALS(generate_metadata_file(bulk_load_info_path));
diff --git a/src/utils/filesystem.cpp b/src/utils/filesystem.cpp
index d0d439664..ec414767c 100644
--- a/src/utils/filesystem.cpp
+++ b/src/utils/filesystem.cpp
@@ -41,6 +41,7 @@
#include <unistd.h>
#include <memory>
+#include "absl/strings/string_view.h"
#include "utils/defer.h"
#include "utils/env.h"
#include "utils/fail_point.h"
@@ -48,7 +49,6 @@
#include "utils/fmt_logging.h"
#include "utils/ports.h"
#include "utils/safe_strerror_posix.h"
-#include "absl/strings/string_view.h"
#define getcwd_ getcwd
#define rmdir_ rmdir
diff --git a/src/utils/fmt_logging.h b/src/utils/fmt_logging.h
index 2e40c8279..62043a2d0 100644
--- a/src/utils/fmt_logging.h
+++ b/src/utils/fmt_logging.h
@@ -275,16 +275,26 @@ inline const char *null_str_printer(const char *s) { return s == nullptr ? "(nul
LOG_AND_RETURN_NOT_TRUE(level, _err == ::dsn::ERR_OK, _err, __VA_ARGS__); \
} while (0)
-// Return the given rocksdb::Status 's' if it is not OK.
-#define LOG_AND_RETURN_NOT_RDB_OK(level, s, ...) \
+// Return the given rocksdb::Status of 'exp' if it is not OK.
+#define LOG_AND_RETURN_NOT_RDB_OK(level, exp, ...) \
do { \
- const auto &_s = (s); \
+ const auto &_s = (exp); \
if (dsn_unlikely(!_s.ok())) { \
LOG_##level("{}: {}", _s.ToString(), fmt::format(__VA_ARGS__)); \
return _s; \
} \
} while (0)
+// Return the given 'err' code if 'exp' is not OK.
+#define LOG_AND_RETURN_CODE_NOT_RDB_OK(level, exp, err, ...) \
+ do { \
+ const auto &_s = (exp); \
+ if (dsn_unlikely(!_s.ok())) { \
+ LOG_##level("{}: {}", _s.ToString(), fmt::format(__VA_ARGS__)); \
+ return err; \
+ } \
+ } while (0)
+
#ifndef NDEBUG
#define DCHECK CHECK
#define DCHECK_NOTNULL CHECK_NOTNULL
diff --git a/src/utils/load_dump_object.h b/src/utils/load_dump_object.h
new file mode 100644
index 000000000..a2ee03167
--- /dev/null
+++ b/src/utils/load_dump_object.h
@@ -0,0 +1,155 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#pragma once
+
+#include <fmt/core.h>
+#include <nlohmann/json.hpp>
+#include <nlohmann/json_fwd.hpp>
+#include <rocksdb/env.h>
+#include <rocksdb/slice.h>
+#include <initializer_list>
+#include <map>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "common/json_helper.h"
+#include "utils/blob.h"
+#include "utils/defer.h"
+#include "utils/env.h"
+#include "utils/error_code.h"
+#include "utils/filesystem.h"
+#include "utils/fmt_logging.h"
+
+namespace dsn {
+namespace utils {
+
+// Write 'data' to path 'file_path', while 'type' decide whether to encrypt the data.
+template <class T>
+error_code write_data_to_file(const std::string &file_path, const T &data, const FileDataType &type)
+{
+ const std::string tmp_file_path = fmt::format("{}.tmp", file_path);
+ auto cleanup = defer([tmp_file_path]() { filesystem::remove_path(tmp_file_path); });
+ LOG_AND_RETURN_CODE_NOT_RDB_OK(
+ ERROR,
+ rocksdb::WriteStringToFile(PegasusEnv(type),
+ rocksdb::Slice(data.data(), data.length()),
+ tmp_file_path,
+ /* should_sync */ true),
+ ERR_FILE_OPERATION_FAILED,
+ "write file '{}' failed",
+ tmp_file_path);
+ LOG_AND_RETURN_NOT_TRUE(ERROR,
+ filesystem::rename_path(tmp_file_path, file_path),
+ ERR_FILE_OPERATION_FAILED,
+ "move file from '{}' to '{}' failed",
+ tmp_file_path,
+ file_path);
+ return ERR_OK;
+}
+
+// Load a object from the file in 'file_path' to 'obj', the file content must be in JSON format.
+// The object T must use the marco DEFINE_JSON_SERIALIZATION(...) when defining, which implement
+// the RapidJson APIs.
+template <class T>
+error_code load_rjobj_from_file(const std::string &file_path, T *obj)
+{
+ LOG_AND_RETURN_NOT_TRUE(ERROR,
+ filesystem::path_exists(file_path),
+ ERR_PATH_NOT_FOUND,
+ "file '{}' not exist",
+ file_path);
+ std::string data;
+ LOG_AND_RETURN_CODE_NOT_RDB_OK(
+ ERROR,
+ rocksdb::ReadFileToString(PegasusEnv(FileDataType::kSensitive), file_path, &data),
+ ERR_FILE_OPERATION_FAILED,
+ "read file '{}' failed",
+ file_path);
+ LOG_AND_RETURN_NOT_TRUE(
+ ERROR,
+ json::json_forwarder<T>::decode(blob::create_from_bytes(std::move(data)), *obj),
+ ERR_CORRUPTION,
+ "decode JSON from file '{}' failed",
+ file_path);
+ return ERR_OK;
+}
+
+// Dump the object to the file in 'file_path' according to 'obj', the file content will be in JSON
+// format.
+// The object T must use the marco DEFINE_JSON_SERIALIZATION(...) when defining, which implement
+// the RapidJson APIs.
+template <class T>
+error_code dump_rjobj_to_file(const T &obj, const std::string &file_path)
+{
+ const auto data = json::json_forwarder<T>::encode(obj);
+ LOG_AND_RETURN_NOT_OK(ERROR,
+ write_data_to_file(file_path, data, FileDataType::kSensitive),
+ "dump content to '{}' failed",
+ file_path);
+ return ERR_OK;
+}
+
+// Similar to load_rjobj_from_file, but the object T must use the
+// marco NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(...) when defining,
+// which implement the NlohmannJson APIs.
+template <class T>
+error_code load_njobj_from_file(const std::string &file_path, T *obj)
+{
+ LOG_AND_RETURN_NOT_TRUE(ERROR,
+ filesystem::path_exists(file_path),
+ ERR_PATH_NOT_FOUND,
+ "file '{}' not exist",
+ file_path);
+ std::string data;
+ LOG_AND_RETURN_CODE_NOT_RDB_OK(
+ ERROR,
+ rocksdb::ReadFileToString(PegasusEnv(FileDataType::kSensitive), file_path, &data),
+ ERR_FILE_OPERATION_FAILED,
+ "read file '{}' failed",
+ file_path);
+ try {
+ nlohmann::json::parse(data).get_to(*obj);
+ } catch (nlohmann::json::exception &exp) {
+ LOG_WARNING("decode JSON from file '{}' failed, exception = {}, data = [{}]",
+ file_path,
+ exp.what(),
+ data);
+ return ERR_CORRUPTION;
+ }
+ return ERR_OK;
+}
+
+// Similar to dump_rjobj_to_file, but the object T must use the
+// marco NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(...) when defining,
+// which implement the NlohmannJson APIs.
+template <class T>
+error_code dump_njobj_to_file(const T &obj, const std::string &file_path)
+{
+ const auto data = nlohmann::json(obj).dump();
+ LOG_AND_RETURN_NOT_OK(ERROR,
+ write_data_to_file(file_path, data, FileDataType::kSensitive),
+ "dump content to '{}' failed",
+ file_path);
+ return ERR_OK;
+}
+
+} // namespace utils
+} // namespace dsn
diff --git a/src/utils/test/load_dump_object_test.cpp b/src/utils/test/load_dump_object_test.cpp
new file mode 100644
index 000000000..4b84de33c
--- /dev/null
+++ b/src/utils/test/load_dump_object_test.cpp
@@ -0,0 +1,115 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "utils/load_dump_object.h"
+
+#include <nlohmann/detail/macro_scope.hpp>
+#include <rocksdb/status.h>
+#include <algorithm>
+#include <cstdint>
+
+#include "gtest/gtest.h"
+
+namespace dsn {
+namespace utils {
+struct nlohmann_json_struct;
+struct rapid_json_struct;
+
+#define STRUCT_CONTENT(T) \
+ int64_t a; \
+ std::string b; \
+ std::vector<int64_t> c; \
+ bool operator==(const T &other) const { return a == other.a && b == other.b && c == other.c; }
+
+struct nlohmann_json_struct
+{
+ STRUCT_CONTENT(nlohmann_json_struct);
+};
+NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(nlohmann_json_struct, a, b, c);
+
+TEST(load_dump_object, nlohmann_json_struct_normal_test)
+{
+ const std::string path("nlohmann_json_struct_test");
+ nlohmann_json_struct obj;
+ obj.a = 123;
+ obj.b = "hello world";
+ obj.c = std::vector<int64_t>({1, 3, 5, 2, 4});
+ ASSERT_EQ(ERR_OK, dump_njobj_to_file(obj, path));
+ nlohmann_json_struct obj2;
+ ASSERT_EQ(ERR_OK, load_njobj_from_file(path, &obj2));
+ ASSERT_EQ(obj, obj2);
+}
+
+TEST(load_dump_object, nlohmann_json_struct_load_failed_test)
+{
+ const std::string path("nlohmann_json_struct_test_bad");
+ ASSERT_TRUE(filesystem::remove_path(path));
+
+ nlohmann_json_struct obj;
+ ASSERT_EQ(ERR_PATH_NOT_FOUND, load_njobj_from_file(path, &obj));
+
+ auto s =
+ rocksdb::WriteStringToFile(dsn::utils::PegasusEnv(dsn::utils::FileDataType::kSensitive),
+ rocksdb::Slice("invalid data"),
+ path,
+ /* should_sync */ true);
+ ASSERT_TRUE(s.ok()) << s.ToString();
+
+ ASSERT_EQ(ERR_CORRUPTION, load_njobj_from_file(path, &obj));
+}
+
+struct rapid_json_struct
+{
+ STRUCT_CONTENT(rapid_json_struct);
+ DEFINE_JSON_SERIALIZATION(a, b, c);
+};
+
+TEST(load_dump_object, rapid_json_struct_test)
+{
+ const std::string path("rapid_json_struct_test");
+ rapid_json_struct obj;
+ obj.a = 123;
+ obj.b = "hello world";
+ obj.c = std::vector<int64_t>({1, 3, 5, 2, 4});
+ ASSERT_EQ(ERR_OK, dump_rjobj_to_file(obj, path));
+ rapid_json_struct obj2;
+ ASSERT_EQ(ERR_OK, load_rjobj_from_file(path, &obj2));
+ ASSERT_EQ(obj, obj2);
+}
+
+TEST(load_dump_object, rapid_json_struct_load_failed_test)
+{
+ const std::string path("rapid_json_struct_test_bad");
+ ASSERT_TRUE(filesystem::remove_path(path));
+
+ rapid_json_struct obj;
+ ASSERT_EQ(ERR_PATH_NOT_FOUND, load_rjobj_from_file(path, &obj));
+
+ auto s =
+ rocksdb::WriteStringToFile(dsn::utils::PegasusEnv(dsn::utils::FileDataType::kSensitive),
+ rocksdb::Slice("invalid data"),
+ path,
+ /* should_sync */ true);
+ ASSERT_TRUE(s.ok()) << s.ToString();
+
+ ASSERT_EQ(ERR_CORRUPTION, load_rjobj_from_file(path, &obj));
+}
+
+} // namespace utils
+} // namespace dsn
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pegasus.apache.org
For additional commands, e-mail: commits-help@pegasus.apache.org