You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@resilientdb.apache.org by ju...@apache.org on 2025/12/10 19:26:51 UTC
(incubator-resilientdb) branch master updated: Support Leveldb with Recovery Data locally (#208)
This is an automated email from the ASF dual-hosted git repository.
junchao pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-resilientdb.git
The following commit(s) were added to refs/heads/master by this push:
new cfb177f0 Support Leveldb with Recovery Data locally (#208)
cfb177f0 is described below
commit cfb177f0eac541fed44d506ad92bc99caef2467f
Author: cjcchen <ic...@gmail.com>
AuthorDate: Thu Dec 11 03:26:48 2025 +0800
Support Leveldb with Recovery Data locally (#208)
* Chenyi (#201)
* Chenyi lastest executed seq num each replica
* Chenyi lastest executed seq num each replica update file route
* Chenyi update create file
* Chenyi update write in checkpoint
* Chenyi update write in checkpoint
* Chenyi update in checkpoint_manager
* Chenyi update in checkpoint_manager
* Chenyi update in checkpoint_manager
* Chenyi update in checkpoint_manager with ofstream, solved executor_
* Chenyi update in checkpoint_manager with ofstream, solved executor_, with test draft, seems deadlock
* Chenyi update in checkpoint_manager with ofstream, solved executor_, with test draft
* Chenyi update in checkpoint_manager with ofstream, solved executor_, with test draft
* Chenyi update in checkpoint_manager with ofstream, with test draft
---------
Co-authored-by: cyzhoutt <cy...@ucdavis.edu>
* add seq
* add checkpoint recovery
* remove query
* remove query
* remove query
* format
* fix recovery test
* fix recovery test
---------
Co-authored-by: cyzhoutt <cy...@ucdavis.edu>
---
INSTALL.sh | 2 +
WORKSPACE | 12 +-
chain/storage/BUILD | 12 +-
chain/storage/kv_storage_test.cpp | 99 +++++++--
chain/storage/leveldb.cpp | 140 +++++++++++--
chain/storage/leveldb.h | 15 +-
chain/storage/memory_db.cpp | 59 ++++--
chain/storage/memory_db.h | 13 +-
chain/storage/mock_storage.h | 19 +-
chain/storage/proto/kv.proto | 1 +
chain/storage/storage.h | 14 +-
common/lru/BUILD | 6 +-
ecosystem/graphql/WORKSPACE | 2 +-
.../graphql/service/http_server/crow_service.cpp | 230 ++++++++++-----------
.../graphql/service/http_server/crow_service.h | 12 +-
.../service/http_server/crow_service_test.cpp | 6 +-
.../service/http_server/example/crow_example.cpp | 2 +-
.../http_server/example/pistache_example.cpp | 2 +-
.../service/http_server/sdk_transaction.cpp | 2 +-
.../graphql/service/http_server/sdk_transaction.h | 2 +-
.../service/kv_service/kv_service_tools.cpp | 5 +-
.../kv_service/kv_service_transaction_manager.cpp | 6 +-
.../kv_service/kv_service_transaction_manager.h | 11 +-
.../graphql/service/kv_service/py_verificator.cpp | 2 +-
.../graphql/service/kv_service/py_verificator.h | 4 +-
.../graphql/service/kv_service/resdb_kv_client.cpp | 7 +-
.../graphql/service/kv_service/resdb_kv_client.h | 4 +-
ecosystem/graphql/service/pybind_sample/client.cpp | 12 +-
executor/common/transaction_manager.cpp | 14 ++
executor/common/transaction_manager.h | 13 +-
executor/contract/executor/contract_executor.cpp | 17 +-
executor/contract/executor/contract_executor.h | 2 +-
.../contract/executor/contract_executor_test.cpp | 23 +--
executor/contract/manager/BUILD | 7 +-
executor/contract/manager/contract_manager.cpp | 3 +-
executor/contract/manager/contract_manager.h | 4 +-
.../contract/manager/contract_manager_test.cpp | 4 +-
executor/contract/manager/evm_state.h | 1 -
executor/contract/manager/global_state.cpp | 27 +--
executor/contract/manager/global_state.h | 1 -
executor/contract/manager/global_view.cpp | 1 -
executor/contract/manager/global_view.h | 2 +-
executor/kv/BUILD | 2 +-
executor/kv/kv_executor.cpp | 47 ++---
executor/kv/kv_executor.h | 3 +-
interface/kv/contract_client.cpp | 14 +-
interface/kv/contract_client.h | 8 +-
platform/config/BUILD | 11 +-
platform/config/resdb_config.h | 1 -
platform/config/resdb_config_test.cpp | 11 +-
platform/config/resdb_config_utils.cpp | 21 +-
platform/config/resdb_config_utils.h | 2 -
platform/consensus/checkpoint/checkpoint.h | 1 +
platform/consensus/checkpoint/mock_checkpoint.h | 1 +
.../consensus/execution/transaction_executor.cpp | 138 +++++++------
.../consensus/execution/transaction_executor.h | 7 +-
platform/consensus/ordering/pbft/BUILD | 2 +-
.../consensus/ordering/pbft/checkpoint_manager.cpp | 164 +++++++++------
.../consensus/ordering/pbft/checkpoint_manager.h | 19 +-
platform/consensus/ordering/pbft/commitment.cpp | 4 +-
.../ordering/pbft/consensus_manager_pbft.cpp | 106 +++++++++-
.../ordering/pbft/consensus_manager_pbft.h | 10 +
.../ordering/pbft/lock_free_collector_pool.cpp | 12 ++
.../ordering/pbft/lock_free_collector_pool.h | 1 +
.../consensus/ordering/pbft/message_manager.cpp | 32 +--
platform/consensus/ordering/pbft/message_manager.h | 8 +-
platform/consensus/ordering/pbft/query.cpp | 48 +++--
platform/consensus/ordering/pbft/query.h | 6 +-
platform/consensus/ordering/pbft/query_test.cpp | 4 +-
.../ordering/pbft/transaction_collector.cpp | 4 +-
platform/consensus/recovery/recovery.cpp | 109 +++++++++-
platform/consensus/recovery/recovery.h | 16 +-
platform/consensus/recovery/recovery_test.cpp | 21 +-
platform/networkstrate/replica_communicator.cpp | 74 +++----
platform/networkstrate/replica_communicator.h | 11 +-
platform/proto/resdb.proto | 4 +-
platform/statistic/BUILD | 2 +-
platform/statistic/set_random_data.cpp | 4 +-
scripts/deploy/config/kv_server.conf | 10 +-
scripts/deploy/script/deploy.sh | 5 +-
scripts/format.sh | 1 +
service/contract/BUILD | 2 +-
service/contract/contract_service.cpp | 3 +-
service/kv/BUILD | 3 +-
service/kv/kv_service.cpp | 13 +-
.../tools/contract/api_tools/contract_tools.cpp | 50 +++--
service/tools/kv/api_tools/BUILD | 3 +-
.../tools/kv/api_tools/contract_service_tools.cpp | 102 ++++-----
third_party/BUILD | 2 -
tools/generate_region_config.py | 1 +
90 files changed, 1250 insertions(+), 693 deletions(-)
diff --git a/INSTALL.sh b/INSTALL.sh
index 9a5f742c..b7c1e9cd 100755
--- a/INSTALL.sh
+++ b/INSTALL.sh
@@ -62,3 +62,5 @@ bazel build @com_github_bazelbuild_buildtools//buildifier:buildifier
sudo apt-get install python3.10-dev -y
sudo apt-get install python3-dev -y
+
+
diff --git a/WORKSPACE b/WORKSPACE
index e05017f5..b5071813 100644
--- a/WORKSPACE
+++ b/WORKSPACE
@@ -22,17 +22,25 @@ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "hedron_compile_commands",
+ strip_prefix = "bazel-compile-commands-extractor-4f28899228fb3ad0126897876f147ca15026151e",
#Replace the commit hash (4f28899228fb3ad0126897876f147ca15026151e) with the latest commit hash from the repo
url = "https://github.com/hedronvision/bazel-compile-commands-extractor/archive/4f28899228fb3ad0126897876f147ca15026151e.tar.gz",
- strip_prefix = "bazel-compile-commands-extractor-4f28899228fb3ad0126897876f147ca15026151e",
)
+
load("@hedron_compile_commands//:workspace_setup.bzl", "hedron_compile_commands_setup")
+
hedron_compile_commands_setup()
+
load("@hedron_compile_commands//:workspace_setup_transitive.bzl", "hedron_compile_commands_setup_transitive")
+
hedron_compile_commands_setup_transitive()
+
load("@hedron_compile_commands//:workspace_setup_transitive_transitive.bzl", "hedron_compile_commands_setup_transitive_transitive")
+
hedron_compile_commands_setup_transitive_transitive()
+
load("@hedron_compile_commands//:workspace_setup_transitive_transitive_transitive.bzl", "hedron_compile_commands_setup_transitive_transitive_transitive")
+
hedron_compile_commands_setup_transitive_transitive_transitive()
load("//:repositories.bzl", "nexres_repositories")
@@ -210,7 +218,7 @@ http_archive(
http_archive(
name = "pybind11_bazel",
strip_prefix = "pybind11_bazel-2.11.1.bzl.1",
- urls = ["https://github.com/pybind/pybind11_bazel/archive/refs/tags/v2.11.1.bzl.1.zip"]
+ urls = ["https://github.com/pybind/pybind11_bazel/archive/refs/tags/v2.11.1.bzl.1.zip"],
)
http_archive(
diff --git a/chain/storage/BUILD b/chain/storage/BUILD
index a86c2a7f..b2e0dfb3 100644
--- a/chain/storage/BUILD
+++ b/chain/storage/BUILD
@@ -60,24 +60,24 @@ cc_library(
cc_test(
name = "kv_storage_test",
+ size = "small", # Set the size to "small"
+ timeout = "short", # Set the timeout to "short"
srcs = ["kv_storage_test.cpp"],
deps = [
":leveldb",
":memory_db",
"//common/test:test_main",
],
- timeout = "short", # Set the timeout to "short"
- size = "small", # Set the size to "small"
)
cc_test(
name = "leveldb_test",
+ size = "small", # Set the size to "small"
+ timeout = "short", # Set the timeout to "short"
srcs = ["leveldb_test.cpp"],
deps = [
":leveldb",
- "//platform/statistic:stats",
"//common/test:test_main",
+ "//platform/statistic:stats",
],
- timeout = "short", # Set the timeout to "short"
- size = "small", # Set the size to "small"
-)
\ No newline at end of file
+)
diff --git a/chain/storage/kv_storage_test.cpp b/chain/storage/kv_storage_test.cpp
index 2e55161f..6ffe1e42 100644
--- a/chain/storage/kv_storage_test.cpp
+++ b/chain/storage/kv_storage_test.cpp
@@ -103,7 +103,7 @@ TEST_P(KVStorageTest, SetValueWithVersion) {
TEST_P(KVStorageTest, GetAllValueWithVersion) {
{
- std::map<std::string, std::pair<std::string, int> > expected_list{
+ std::map<std::string, std::pair<std::string, int>> expected_list{
std::make_pair("test_key", std::make_pair("test_value", 1))};
EXPECT_EQ(storage->SetValueWithVersion("test_key", "test_value", 0), 0);
@@ -111,14 +111,14 @@ TEST_P(KVStorageTest, GetAllValueWithVersion) {
}
{
- std::map<std::string, std::pair<std::string, int> > expected_list{
+ std::map<std::string, std::pair<std::string, int>> expected_list{
std::make_pair("test_key", std::make_pair("test_value_v2", 2))};
EXPECT_EQ(storage->SetValueWithVersion("test_key", "test_value_v2", 1), 0);
EXPECT_EQ(storage->GetAllItems(), expected_list);
}
{
- std::map<std::string, std::pair<std::string, int> > expected_list{
+ std::map<std::string, std::pair<std::string, int>> expected_list{
std::make_pair("test_key_v1", std::make_pair("test_value1", 1)),
std::make_pair("test_key", std::make_pair("test_value_v2", 2))};
EXPECT_EQ(storage->SetValueWithVersion("test_key_v1", "test_value1", 0), 0);
@@ -126,6 +126,79 @@ TEST_P(KVStorageTest, GetAllValueWithVersion) {
}
}
+TEST_P(KVStorageTest, SetValueWithSeq) {
+ EXPECT_EQ(storage->SetValueWithSeq("test_key", "test_value", 2), 0);
+
+ EXPECT_EQ(storage->SetValueWithSeq("test_key", "test_value", 1), -2);
+
+ EXPECT_EQ(storage->GetValueWithSeq("test_key", static_cast<uint64_t>(1)),
+ std::make_pair(std::string(""), static_cast<uint64_t>(0)));
+ EXPECT_EQ(
+ storage->GetValueWithSeq("test_key", 2),
+ std::make_pair(std::string("test_value"), static_cast<uint64_t>(2)));
+
+ EXPECT_EQ(storage->SetValueWithSeq("test_key", "test_value_v2", 3), 0);
+
+ EXPECT_EQ(storage->GetValueWithSeq("test_key", 1),
+ std::make_pair(std::string(""), static_cast<uint64_t>(0)));
+
+ EXPECT_EQ(
+ storage->GetValueWithSeq("test_key", 2),
+ std::make_pair(std::string("test_value"), static_cast<uint64_t>(2)));
+
+ EXPECT_EQ(
+ storage->GetValueWithSeq("test_key", 3),
+ std::make_pair(std::string("test_value_v2"), static_cast<uint64_t>(3)));
+
+ EXPECT_EQ(storage->GetValueWithSeq("test_key", 4),
+ std::make_pair(std::string(""), static_cast<uint64_t>(0)));
+}
+
+TEST_P(KVStorageTest, GetAllValueWithSeq) {
+ typedef std::vector<std::pair<std::string, uint64_t>> List;
+ {
+ std::map<std::string, std::vector<std::pair<std::string, uint64_t>>>
+ expected_list{
+ std::make_pair("test_key", List{std::make_pair("test_value", 1)})};
+
+ EXPECT_EQ(storage->SetValueWithSeq("test_key", "test_value", 1), 0);
+ EXPECT_EQ(storage->GetAllItemsWithSeq(), expected_list);
+ }
+
+ {
+ std::map<std::string, std::vector<std::pair<std::string, uint64_t>>>
+ expected_list{std::make_pair("test_key",
+ List{std::make_pair("test_value", 1),
+ std::make_pair("test_value_v2", 2)})};
+ EXPECT_EQ(storage->SetValueWithSeq("test_key", "test_value_v2", 2), 0);
+ EXPECT_EQ(storage->GetAllItemsWithSeq(), expected_list);
+ }
+
+ {
+ std::map<std::string, std::vector<std::pair<std::string, uint64_t>>>
+ expected_list{std::make_pair("test_key_v1",
+ List{std::make_pair("test_value1", 1)}),
+ std::make_pair("test_key",
+ List{std::make_pair("test_value", 1),
+ std::make_pair("test_value_v2", 2)})};
+ EXPECT_EQ(storage->SetValueWithSeq("test_key_v1", "test_value1", 1), 0);
+ EXPECT_EQ(storage->GetAllItemsWithSeq(), expected_list);
+ }
+
+ {
+ storage->SetMaxHistoryNum(2);
+ std::map<std::string, std::vector<std::pair<std::string, uint64_t>>>
+ expected_list{
+ std::make_pair("test_key_v1",
+ List{std::make_pair("test_value1", 1)}),
+ std::make_pair("test_key", List{std::make_pair("test_value3", 3),
+ std::make_pair("test_value4", 4)})};
+ EXPECT_EQ(storage->SetValueWithSeq("test_key", "test_value3", 3), 0);
+ EXPECT_EQ(storage->SetValueWithSeq("test_key", "test_value4", 4), 0);
+ EXPECT_EQ(storage->GetAllItemsWithSeq(), expected_list);
+ }
+}
+
TEST_P(KVStorageTest, GetKeyRange) {
EXPECT_EQ(storage->SetValueWithVersion("1", "value1", 0), 0);
EXPECT_EQ(storage->SetValueWithVersion("2", "value2", 0), 0);
@@ -133,7 +206,7 @@ TEST_P(KVStorageTest, GetKeyRange) {
EXPECT_EQ(storage->SetValueWithVersion("4", "value4", 0), 0);
{
- std::map<std::string, std::pair<std::string, int> > expected_list{
+ std::map<std::string, std::pair<std::string, int>> expected_list{
std::make_pair("1", std::make_pair("value1", 1)),
std::make_pair("2", std::make_pair("value2", 1)),
std::make_pair("3", std::make_pair("value3", 1)),
@@ -143,7 +216,7 @@ TEST_P(KVStorageTest, GetKeyRange) {
EXPECT_EQ(storage->SetValueWithVersion("3", "value3_1", 1), 0);
{
- std::map<std::string, std::pair<std::string, int> > expected_list{
+ std::map<std::string, std::pair<std::string, int>> expected_list{
std::make_pair("1", std::make_pair("value1", 1)),
std::make_pair("2", std::make_pair("value2", 1)),
std::make_pair("3", std::make_pair("value3_1", 2)),
@@ -151,7 +224,7 @@ TEST_P(KVStorageTest, GetKeyRange) {
EXPECT_EQ(storage->GetKeyRange("1", "4"), expected_list);
}
{
- std::map<std::string, std::pair<std::string, int> > expected_list{
+ std::map<std::string, std::pair<std::string, int>> expected_list{
std::make_pair("1", std::make_pair("value1", 1)),
std::make_pair("2", std::make_pair("value2", 1)),
std::make_pair("3", std::make_pair("value3_1", 2)),
@@ -159,14 +232,14 @@ TEST_P(KVStorageTest, GetKeyRange) {
EXPECT_EQ(storage->GetKeyRange("1", "3"), expected_list);
}
{
- std::map<std::string, std::pair<std::string, int> > expected_list{
+ std::map<std::string, std::pair<std::string, int>> expected_list{
std::make_pair("2", std::make_pair("value2", 1)),
std::make_pair("3", std::make_pair("value3_1", 2)),
std::make_pair("4", std::make_pair("value4", 1))};
EXPECT_EQ(storage->GetKeyRange("2", "4"), expected_list);
}
{
- std::map<std::string, std::pair<std::string, int> > expected_list{
+ std::map<std::string, std::pair<std::string, int>> expected_list{
std::make_pair("1", std::make_pair("value1", 1)),
std::make_pair("2", std::make_pair("value2", 1)),
std::make_pair("3", std::make_pair("value3_1", 2)),
@@ -174,7 +247,7 @@ TEST_P(KVStorageTest, GetKeyRange) {
EXPECT_EQ(storage->GetKeyRange("0", "5"), expected_list);
}
{
- std::map<std::string, std::pair<std::string, int> > expected_list{
+ std::map<std::string, std::pair<std::string, int>> expected_list{
std::make_pair("2", std::make_pair("value2", 1)),
std::make_pair("3", std::make_pair("value3_1", 2)),
};
@@ -184,11 +257,11 @@ TEST_P(KVStorageTest, GetKeyRange) {
TEST_P(KVStorageTest, GetHistory) {
{
- std::vector<std::pair<std::string, int> > expected_list{};
+ std::vector<std::pair<std::string, int>> expected_list{};
EXPECT_EQ(storage->GetHistory("1", 1, 5), expected_list);
}
{
- std::vector<std::pair<std::string, int> > expected_list{
+ std::vector<std::pair<std::string, int>> expected_list{
std::make_pair("value3", 3), std::make_pair("value2", 2),
std::make_pair("value1", 1)};
@@ -200,7 +273,7 @@ TEST_P(KVStorageTest, GetHistory) {
}
{
- std::vector<std::pair<std::string, int> > expected_list{
+ std::vector<std::pair<std::string, int>> expected_list{
std::make_pair("value5", 5), std::make_pair("value4", 4),
std::make_pair("value3", 3), std::make_pair("value2", 2),
std::make_pair("value1", 1)};
@@ -214,7 +287,7 @@ TEST_P(KVStorageTest, GetHistory) {
}
{
- std::vector<std::pair<std::string, int> > expected_list{
+ std::vector<std::pair<std::string, int>> expected_list{
std::make_pair("value7", 7), std::make_pair("value6", 6)};
EXPECT_EQ(storage->GetTopHistory("1", 2), expected_list);
diff --git a/chain/storage/leveldb.cpp b/chain/storage/leveldb.cpp
index f6122b5a..de49376e 100644
--- a/chain/storage/leveldb.cpp
+++ b/chain/storage/leveldb.cpp
@@ -64,7 +64,9 @@ ResLevelDB::ResLevelDB(std::optional<LevelDBInfo> config) {
LOG(ERROR) << "initialized block cache" << std::endl;
}
global_stats_ = Stats::GetGlobalStats();
+ last_ckpt_ = 0;
CreateDB(path);
+ last_ckpt_ = GetLastCheckpointInternal();
}
void ResLevelDB::CreateDB(const std::string& path) {
@@ -93,6 +95,69 @@ ResLevelDB::~ResLevelDB() {
}
}
+int ResLevelDB::SetValueWithSeq(const std::string& key,
+ const std::string& value, uint64_t seq) {
+ std::string value_str = GetValue(key);
+ ValueHistory history;
+ if (!history.ParseFromString(value_str)) {
+ LOG(ERROR) << "old_value parse fail";
+ return -2;
+ }
+
+ uint64_t last_seq = 0;
+ if (history.value_size() > 0) {
+ last_seq = history.value(history.value_size() - 1).seq();
+ }
+
+ if (last_seq > seq) {
+ LOG(ERROR) << "seq is small, last:" << last_seq << " new seq:" << seq;
+ UpdateLastCkpt(last_seq);
+ return -2;
+ }
+
+ Value* new_value = history.add_value();
+ new_value->set_value(value);
+ new_value->set_seq(seq);
+
+ while (history.value_size() > max_history_) {
+ history.mutable_value()->erase(history.mutable_value()->begin());
+ }
+
+ LOG(ERROR) << " set value, string:" << key << " seq:" << seq
+ << " last seq:" << last_seq;
+ history.SerializeToString(&value_str);
+ int ret = SetValue(key, value_str);
+ if (ret) {
+ return ret;
+ }
+ UpdateLastCkpt(seq);
+ return 0;
+}
+
+std::pair<std::string, uint64_t> ResLevelDB::GetValueWithSeq(
+ const std::string& key, uint64_t seq) {
+ std::string value_str = GetValue(key);
+ ValueHistory history;
+ if (!history.ParseFromString(value_str)) {
+ LOG(ERROR) << "old_value parse fail";
+ return std::make_pair("", 0);
+ }
+ if (history.value_size() == 0) {
+ return std::make_pair("", 0);
+ }
+ if (seq > 0) {
+ for (int i = history.value_size() - 1; i >= 0; --i) {
+ if (history.value(i).seq() == seq) {
+ return std::make_pair(history.value(i).value(), history.value(i).seq());
+ }
+ }
+ return std::make_pair("", 0);
+ }
+ int last_idx = history.value_size() - 1;
+ return std::make_pair(history.value(last_idx).value(),
+ history.value(last_idx).seq());
+}
+
int ResLevelDB::SetValue(const std::string& key, const std::string& value) {
if (block_cache_) {
block_cache_->Put(key, value);
@@ -133,21 +198,6 @@ std::string ResLevelDB::GetValue(const std::string& key) {
return value;
}
-std::string ResLevelDB::GetAllValues(void) {
- std::string values = "[";
- leveldb::Iterator* it = db_->NewIterator(leveldb::ReadOptions());
- bool first_iteration = true;
- for (it->SeekToFirst(); it->Valid(); it->Next()) {
- if (!first_iteration) values.append(",");
- first_iteration = false;
- values.append(it->value().ToString());
- }
- values.append("]");
-
- delete it;
- return values;
-}
-
std::string ResLevelDB::GetRange(const std::string& min_key,
const std::string& max_key) {
std::string values = "[";
@@ -243,6 +293,30 @@ std::pair<std::string, int> ResLevelDB::GetValueWithVersion(
history.value(last_idx).version());
}
+// Return a map of <key, <value, version>>
+std::map<std::string, std::vector<std::pair<std::string, uint64_t>>>
+ResLevelDB::GetAllItemsWithSeq() {
+ std::map<std::string, std::vector<std::pair<std::string, uint64_t>>> resp;
+
+ leveldb::Iterator* it = db_->NewIterator(leveldb::ReadOptions());
+ for (it->SeekToFirst(); it->Valid(); it->Next()) {
+ ValueHistory history;
+ if (!history.ParseFromString(it->value().ToString()) ||
+ history.value_size() == 0) {
+ LOG(ERROR) << "old_value parse fail";
+ continue;
+ }
+ LOG(ERROR) << "history value size:" << history.value_size();
+ for (auto value : history.value()) {
+ resp[it->key().ToString()].push_back(
+ std::make_pair(value.value(), value.seq()));
+ }
+ }
+ delete it;
+
+ return resp;
+}
+
// Return a map of <key, <value, version>>
std::map<std::string, std::pair<std::string, int>> ResLevelDB::GetAllItems() {
std::map<std::string, std::pair<std::string, int>> resp;
@@ -330,5 +404,41 @@ std::vector<std::pair<std::string, int>> ResLevelDB::GetTopHistory(
return resp;
}
+const std::string ckpt_key = "leveldb_checkpoint";
+
+void ResLevelDB::UpdateLastCkpt(uint64_t seq) {
+ LOG(ERROR) << " update ckpt seq:" << seq << " last:" << last_ckpt_
+ << " update time:" << update_time_;
+ if (last_ckpt_ > seq) {
+ return;
+ }
+ last_ckpt_ = seq;
+ update_time_++;
+ if (update_time_ % 100 == 0 && last_ckpt_ > 0) {
+ SetLastCheckpoint(last_ckpt_);
+ update_time_ = 0;
+ }
+}
+
+int ResLevelDB::SetLastCheckpoint(uint64_t ckpt) {
+ LOG(ERROR) << " update last ckpt :" << ckpt;
+ return SetValue(ckpt_key, std::to_string(ckpt));
+}
+
+uint64_t ResLevelDB::GetLastCheckpointInternal() {
+ std::string value = GetValue(ckpt_key);
+ if (value.empty()) {
+ return 0;
+ }
+ return std::stoll(value);
+}
+
+uint64_t ResLevelDB::GetLastCheckpoint() {
+ if (last_ckpt_ > 0) {
+ return last_ckpt_;
+ }
+ return GetLastCheckpointInternal();
+}
+
} // namespace storage
} // namespace resdb
diff --git a/chain/storage/leveldb.h b/chain/storage/leveldb.h
index 6103ec20..67ec7a40 100644
--- a/chain/storage/leveldb.h
+++ b/chain/storage/leveldb.h
@@ -43,9 +43,12 @@ class ResLevelDB : public Storage {
ResLevelDB(std::optional<LevelDBInfo> config_data = std::nullopt);
virtual ~ResLevelDB();
+ int SetValueWithSeq(const std::string& key, const std::string& value,
+ uint64_t seq) override;
int SetValue(const std::string& key, const std::string& value) override;
std::string GetValue(const std::string& key) override;
- std::string GetAllValues(void) override;
+ std::pair<std::string, uint64_t> GetValueWithSeq(const std::string& key,
+ uint64_t seq) override;
std::string GetRange(const std::string& min_key,
const std::string& max_key) override;
@@ -55,6 +58,8 @@ class ResLevelDB : public Storage {
int version) override;
// Return a map of <key, <value, version>>
+ std::map<std::string, std::vector<std::pair<std::string, uint64_t>>>
+ GetAllItemsWithSeq() override;
std::map<std::string, std::pair<std::string, int>> GetAllItems() override;
std::map<std::string, std::pair<std::string, int>> GetKeyRange(
const std::string& min_key, const std::string& max_key) override;
@@ -71,8 +76,14 @@ class ResLevelDB : public Storage {
bool Flush() override;
+ virtual uint64_t GetLastCheckpoint() override;
+
+ virtual int SetLastCheckpoint(uint64_t ckpt);
+
private:
void CreateDB(const std::string& path);
+ uint64_t GetLastCheckpointInternal();
+ void UpdateLastCkpt(uint64_t seq);
private:
std::unique_ptr<leveldb::DB> db_ = nullptr;
@@ -83,6 +94,8 @@ class ResLevelDB : public Storage {
protected:
Stats* global_stats_ = nullptr;
std::unique_ptr<LRUCache<std::string, std::string>> block_cache_;
+ uint64_t last_ckpt_;
+ int update_time_ = 0;
};
} // namespace storage
diff --git a/chain/storage/memory_db.cpp b/chain/storage/memory_db.cpp
index 2d5b8725..d5e68c55 100644
--- a/chain/storage/memory_db.cpp
+++ b/chain/storage/memory_db.cpp
@@ -33,18 +33,6 @@ int MemoryDB::SetValue(const std::string& key, const std::string& value) {
return 0;
}
-std::string MemoryDB::GetAllValues(void) {
- std::string values = "[";
- bool first_iteration = true;
- for (auto kv : kv_map_) {
- if (!first_iteration) values.append(",");
- first_iteration = false;
- values.append(kv.second);
- }
- values.append("]");
- return values;
-}
-
std::string MemoryDB::GetRange(const std::string& min_key,
const std::string& max_key) {
std::string values = "[";
@@ -69,6 +57,41 @@ std::string MemoryDB::GetValue(const std::string& key) {
}
}
+std::pair<std::string, uint64_t> MemoryDB::GetValueWithSeq(
+ const std::string& key, uint64_t seq) {
+ auto search_it = kv_map_with_seq_.find(key);
+ if (search_it != kv_map_with_seq_.end() && search_it->second.size()) {
+ auto it = search_it->second.end();
+ do {
+ --it;
+ if (it->second == seq) {
+ return *it;
+ }
+ if (it->second < seq) {
+ break;
+ }
+ } while (it != search_it->second.begin());
+ LOG(ERROR) << " key:" << key << " no seq:" << seq;
+ }
+ return std::make_pair("", 0);
+}
+
+int MemoryDB::SetValueWithSeq(const std::string& key, const std::string& value,
+ uint64_t seq) {
+ auto it = kv_map_with_seq_.find(key);
+ if (it != kv_map_with_seq_.end() && it->second.back().second > seq) {
+ LOG(ERROR) << " value seq not match. key:" << key << " db seq:"
+ << (it == kv_map_with_seq_.end() ? 0 : it->second.back().second)
+ << " new seq:" << seq;
+ return -2;
+ }
+ kv_map_with_seq_[key].push_back(std::make_pair(value, seq));
+ while (kv_map_with_seq_[key].size() > max_history_) {
+ kv_map_with_seq_[key].erase(kv_map_with_seq_[key].begin());
+ }
+ return 0;
+}
+
int MemoryDB::SetValueWithVersion(const std::string& key,
const std::string& value, int version) {
auto it = kv_map_with_v_.find(key);
@@ -105,6 +128,18 @@ std::pair<std::string, int> MemoryDB::GetValueWithVersion(
return std::make_pair("", 0);
}
+std::map<std::string, std::vector<std::pair<std::string, uint64_t>>>
+MemoryDB::GetAllItemsWithSeq() {
+ std::map<std::string, std::vector<std::pair<std::string, uint64_t>>> resp;
+ for (const auto& it : kv_map_with_seq_) {
+ LOG(ERROR) << " value num:" << it.second.size();
+ for (const auto& item : it.second) {
+ resp[it.first].push_back(item);
+ }
+ }
+ return resp;
+}
+
std::map<std::string, std::pair<std::string, int>> MemoryDB::GetAllItems() {
std::map<std::string, std::pair<std::string, int>> resp;
diff --git a/chain/storage/memory_db.h b/chain/storage/memory_db.h
index 372f4647..ec138c7a 100644
--- a/chain/storage/memory_db.h
+++ b/chain/storage/memory_db.h
@@ -53,10 +53,13 @@ class MemoryDB : public Storage {
public:
MemoryDB();
- int SetValue(const std::string& key, const std::string& value);
- std::string GetValue(const std::string& key);
+ int SetValueWithSeq(const std::string& key, const std::string& value,
+ uint64_t seq) override;
+ int SetValue(const std::string& key, const std::string& value) override;
+ std::string GetValue(const std::string& key) override;
+ std::pair<std::string, uint64_t> GetValueWithSeq(const std::string& key,
+ uint64_t seq) override;
- std::string GetAllValues() override;
std::string GetRange(const std::string& min_key,
const std::string& max_key) override;
@@ -66,6 +69,8 @@ class MemoryDB : public Storage {
int version) override;
// Return a map of <key, <value, version>>
+ std::map<std::string, std::vector<std::pair<std::string, uint64_t>>>
+ GetAllItemsWithSeq() override;
std::map<std::string, std::pair<std::string, int>> GetAllItems() override;
std::map<std::string, std::pair<std::string, int>> GetKeyRange(
const std::string& min_key, const std::string& max_key) override;
@@ -82,6 +87,8 @@ class MemoryDB : public Storage {
std::unordered_map<std::string, std::string> kv_map_;
std::unordered_map<std::string, std::list<std::pair<std::string, int>>>
kv_map_with_v_;
+ std::unordered_map<std::string, std::list<std::pair<std::string, uint64_t>>>
+ kv_map_with_seq_;
};
} // namespace storage
diff --git a/chain/storage/mock_storage.h b/chain/storage/mock_storage.h
index 963d92bb..6b17c326 100644
--- a/chain/storage/mock_storage.h
+++ b/chain/storage/mock_storage.h
@@ -26,29 +26,36 @@ namespace resdb {
class MockStorage : public Storage {
public:
+ using ValueType = std::pair<std::string, int>;
+ using ValueSeqType = std::pair<std::string, uint64_t>;
+ using ItemsType = std::map<std::string, ValueType>;
+ using ValuesType = std::vector<ValueType>;
+ using ValuesSeqType = std::map<std::string, std::vector<ValueSeqType>>;
+
MOCK_METHOD(int, SetValue, (const std::string& key, const std::string& value),
(override));
MOCK_METHOD(std::string, GetValue, (const std::string& key), (override));
- MOCK_METHOD(std::string, GetAllValues, (), (override));
MOCK_METHOD(std::string, GetRange, (const std::string&, const std::string&),
(override));
+ MOCK_METHOD(ValueSeqType, GetValueWithSeq, (const std::string& key, uint64_t),
+ (override));
MOCK_METHOD(int, SetValueWithVersion,
(const std::string& key, const std::string& value, int version),
(override));
-
- using ValueType = std::pair<std::string, int>;
- using ItemsType = std::map<std::string, ValueType>;
- using ValuesType = std::vector<ValueType>;
+ MOCK_METHOD(int, SetValueWithSeq,
+ (const std::string& key, const std::string& value, uint64_t seq),
+ (override));
MOCK_METHOD(ValueType, GetValueWithVersion,
(const std::string& key, int version), (override));
- MOCK_METHOD(ItemsType, GetAllItems, (), (override));
MOCK_METHOD(ItemsType, GetKeyRange, (const std::string&, const std::string&),
(override));
MOCK_METHOD(ValuesType, GetHistory, (const std::string&, int, int),
(override));
MOCK_METHOD(ValuesType, GetTopHistory, (const std::string&, int), (override));
+ MOCK_METHOD(ItemsType, GetAllItems, (), (override));
+ MOCK_METHOD(ValuesSeqType, GetAllItemsWithSeq, (), (override));
MOCK_METHOD(bool, Flush, (), (override));
};
diff --git a/chain/storage/proto/kv.proto b/chain/storage/proto/kv.proto
index 8466b8dc..319d7fb0 100644
--- a/chain/storage/proto/kv.proto
+++ b/chain/storage/proto/kv.proto
@@ -24,6 +24,7 @@ package resdb.storage;
message Value {
bytes value = 1;
int32 version = 2;
+ uint64 seq = 3;
}
message ValueHistory {
diff --git a/chain/storage/storage.h b/chain/storage/storage.h
index 76e352de..8fa95fee 100644
--- a/chain/storage/storage.h
+++ b/chain/storage/storage.h
@@ -31,8 +31,11 @@ class Storage {
virtual ~Storage() = default;
virtual int SetValue(const std::string& key, const std::string& value) = 0;
+ virtual int SetValueWithSeq(const std::string& key, const std::string& value,
+ uint64_t seq) = 0;
virtual std::string GetValue(const std::string& key) = 0;
- virtual std::string GetAllValues() = 0;
+ virtual std::pair<std::string, uint64_t> GetValueWithSeq(
+ const std::string& key, uint64_t seq) = 0;
virtual std::string GetRange(const std::string& min_key,
const std::string& max_key) = 0;
@@ -42,6 +45,8 @@ class Storage {
const std::string& key, int version) = 0;
// Return a map of <key, <value, version>>
+ virtual std::map<std::string, std::vector<std::pair<std::string, uint64_t>>>
+ GetAllItemsWithSeq() = 0;
virtual std::map<std::string, std::pair<std::string, int>> GetAllItems() = 0;
virtual std::map<std::string, std::pair<std::string, int>> GetKeyRange(
const std::string& min_key, const std::string& max_key) = 0;
@@ -55,6 +60,13 @@ class Storage {
const std::string& key, int number) = 0;
virtual bool Flush() { return true; };
+
+ virtual uint64_t GetLastCheckpoint() { return 0; }
+
+ void SetMaxHistoryNum(int num) { max_history_ = num; }
+
+ protected:
+ uint32_t max_history_ = 10;
};
} // namespace resdb
diff --git a/common/lru/BUILD b/common/lru/BUILD
index ad72bd98..250af522 100644
--- a/common/lru/BUILD
+++ b/common/lru/BUILD
@@ -26,11 +26,11 @@ cc_library(
cc_test(
name = "lru_cache_test",
+ size = "small", # Set the size to "small"
+ timeout = "short", # Set the timeout to "short"
srcs = ["lru_cache_test.cpp"],
deps = [
"//common/lru:lru_cache",
"//common/test:test_main",
],
- timeout = "short", # Set the timeout to "short"
- size = "small", # Set the size to "small"
-)
\ No newline at end of file
+)
diff --git a/ecosystem/graphql/WORKSPACE b/ecosystem/graphql/WORKSPACE
index 2ae0146f..8ebac612 100644
--- a/ecosystem/graphql/WORKSPACE
+++ b/ecosystem/graphql/WORKSPACE
@@ -172,7 +172,7 @@ http_archive(
http_archive(
name = "pybind11_bazel",
strip_prefix = "pybind11_bazel-2.11.1.bzl.1",
- urls = ["https://github.com/pybind/pybind11_bazel/archive/refs/tags/v2.11.1.bzl.1.zip"]
+ urls = ["https://github.com/pybind/pybind11_bazel/archive/refs/tags/v2.11.1.bzl.1.zip"],
)
http_archive(
diff --git a/ecosystem/graphql/service/http_server/crow_service.cpp b/ecosystem/graphql/service/http_server/crow_service.cpp
index 5642ebb7..e7054634 100644
--- a/ecosystem/graphql/service/http_server/crow_service.cpp
+++ b/ecosystem/graphql/service/http_server/crow_service.cpp
@@ -28,32 +28,35 @@
#include <sys/types.h>
#include <unistd.h>
-#include <ctime>
#include <chrono>
+#include <ctime>
#include <fstream>
#include <memory>
+#include <mutex>
#include <string>
#include <thread>
-
-#include <mutex>
#include <unordered_set>
using crow::request;
using crow::response;
using resdb::BatchUserRequest;
-using resdb::ResDBConfig;
-using resdb::ReplicaState;
-using resdb::ResConfigData;
+using resdb::CertificateInfo;
using resdb::KeyInfo;
using resdb::ReplicaInfo;
-using resdb::CertificateInfo;
+using resdb::ReplicaState;
+using resdb::ResConfigData;
+using resdb::ResDBConfig;
namespace sdk {
CrowService::CrowService(ResDBConfig client_config, ResDBConfig server_config,
uint16_t port_num)
- : client_config_(client_config), server_config_(server_config), port_num_(port_num),
- kv_client_(client_config_), state_client_(client_config_), txn_client_(server_config_) {
+ : client_config_(client_config),
+ server_config_(server_config),
+ port_num_(port_num),
+ kv_client_(client_config_),
+ state_client_(client_config_),
+ txn_client_(server_config_) {
GetAllBlocks(100, true, false);
}
@@ -67,26 +70,26 @@ void CrowService::run() {
CROW_ROUTE(app, "/v1/transactions")
([this](const crow::request &req, response &res) {
uint64_t cur_time = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::system_clock::now().time_since_epoch()
- ).count();
+ std::chrono::system_clock::now().time_since_epoch())
+ .count();
if (cur_time < last_db_scan_time + DB_SCAN_TIMEOUT_MS) {
res.code = 503;
res.set_header("Content-Type", "text/plain");
- res.end("Get all transactions functionality on cooldown (" +
- std::to_string(last_db_scan_time + DB_SCAN_TIMEOUT_MS - cur_time) +
- " ms left)");
+ res.end(
+ "Get all transactions functionality on cooldown (" +
+ std::to_string(last_db_scan_time + DB_SCAN_TIMEOUT_MS - cur_time) +
+ " ms left)");
} else {
last_db_scan_time = cur_time;
auto values = kv_client_.GetAllValues();
if (values != nullptr) {
- //LOG(INFO) << "client getallvalues value = " << values->c_str();
+ // LOG(INFO) << "client getallvalues value = " << values->c_str();
// Send updated blocks list to websocket
if (users.size() > 0) {
- for (auto u : users)
- u->send_text("Update blocks");
+ for (auto u : users) u->send_text("Update blocks");
}
num_transactions_++;
@@ -110,8 +113,7 @@ void CrowService::run() {
// Send updated blocks list to websocket
if (users.size() > 0) {
- for (auto u : users)
- u->send_text("Update blocks");
+ for (auto u : users) u->send_text("Update blocks");
}
num_transactions_++;
@@ -135,8 +137,7 @@ void CrowService::run() {
// Send updated blocks list to websocket
if (users.size() > 0) {
- for (auto u : users)
- u->send_text("Update blocks");
+ for (auto u : users) u->send_text("Update blocks");
}
num_transactions_++;
@@ -153,44 +154,43 @@ void CrowService::run() {
// Commit a key-value pair, extracting the id parameter from the JSON
// object and setting the value as the entire JSON object
CROW_ROUTE(app, "/v1/transactions/commit")
- .methods("POST"_method)([this](const request& req) {
- std::string body = req.body;
- LOG(INFO) << "body: " << body;
-
- // Parse transaction JSON
- rapidjson::Document doc;
- doc.Parse(body.c_str());
- if (!doc.IsObject() || !doc.HasMember("id")) {
- response res(400, "Invalid transaction format"); // Bad Request
- res.set_header("Content-Type", "text/plain");
- return res;
- }
- const std::string id = doc["id"].GetString();
- const std::string value = body;
+ .methods("POST"_method)([this](const request &req) {
+ std::string body = req.body;
+ LOG(INFO) << "body: " << body;
+
+ // Parse transaction JSON
+ rapidjson::Document doc;
+ doc.Parse(body.c_str());
+ if (!doc.IsObject() || !doc.HasMember("id")) {
+ response res(400, "Invalid transaction format"); // Bad Request
+ res.set_header("Content-Type", "text/plain");
+ return res;
+ }
+ const std::string id = doc["id"].GetString();
+ const std::string value = body;
- // Set key-value pair in kv server
- int retval = kv_client_.Set(id, value);
+ // Set key-value pair in kv server
+ int retval = kv_client_.Set(id, value);
- if (retval != 0) {
- LOG(ERROR) << "Error when trying to commit id " << id;
- response res(500, "id: " + id);
- res.set_header("Content-Type", "text/plain");
- return res;
- }
- LOG(INFO) << "Set " << id << " to " << value;
+ if (retval != 0) {
+ LOG(ERROR) << "Error when trying to commit id " << id;
+ response res(500, "id: " + id);
+ res.set_header("Content-Type", "text/plain");
+ return res;
+ }
+ LOG(INFO) << "Set " << id << " to " << value;
- // Send updated blocks list to websocket
- if (users.size() > 0) {
- for (auto u : users)
- u->send_text("Update blocks");
- }
+ // Send updated blocks list to websocket
+ if (users.size() > 0) {
+ for (auto u : users) u->send_text("Update blocks");
+ }
- num_transactions_++;
+ num_transactions_++;
- response res(201, "id: " + id); // Created status code
- res.set_header("Content-Type", "text/plain");
- return res;
- });
+ response res(201, "id: " + id); // Created status code
+ res.set_header("Content-Type", "text/plain");
+ return res;
+ });
CROW_ROUTE(app, "/v1/blocks")
([this](const crow::request &req, response &res) {
@@ -237,8 +237,7 @@ void CrowService::run() {
if (request.ParseFromString(txn.second)) {
LOG(INFO) << request.DebugString();
- if (!first_iteration)
- cur_batch_str.append(",");
+ if (!first_iteration) cur_batch_str.append(",");
first_iteration = false;
// id
@@ -255,13 +254,12 @@ void CrowService::run() {
kv_request.ParseFromString(sub_req.request().data());
std::string kv_request_json = ParseKVRequest(kv_request);
- if (!first_transaction)
- cur_batch_str.append(",");
+ if (!first_transaction) cur_batch_str.append(",");
first_transaction = false;
cur_batch_str.append(kv_request_json);
cur_batch_str.append("\n");
}
- cur_batch_str.append("]"); // close transactions list
+ cur_batch_str.append("]"); // close transactions list
// size
cur_batch_str.append(", \"size\": " +
@@ -300,18 +298,18 @@ void CrowService::run() {
// For metadata table on the Explorer
CROW_ROUTE(app, "/populatetable")
- ([this](const crow::request& req, response& res) {
-
+ ([this](const crow::request &req, response &res) {
absl::StatusOr<ReplicaState> state_or = state_client_.GetReplicaState();
- if(!state_or.ok()){
- LOG(ERROR)<<"get state fail";
- res.set_header("Content-Type", "application/json");
- res.end("");
- return;
- }
+ if (!state_or.ok()) {
+ LOG(ERROR) << "get state fail";
+ res.set_header("Content-Type", "application/json");
+ res.end("");
+ return;
+ }
ResConfigData config_data = (*state_or).replica_config();
- ResDBConfig server_config(config_data, ReplicaInfo(), KeyInfo(), CertificateInfo());
+ ResDBConfig server_config(config_data, ReplicaInfo(), KeyInfo(),
+ CertificateInfo());
uint32_t replica_num = server_config.GetReplicaNum();
uint32_t worker_num = server_config.GetWorkerNum();
@@ -322,7 +320,8 @@ void CrowService::run() {
uint32_t output_worker_num = server_config.GetOutputWorkerNum();
int client_timeout_ms = server_config.GetClientTimeoutMs();
int min_data_receive_num = server_config.GetMinDataReceiveNum();
- size_t max_malicious_replica_num = server_config.GetMaxMaliciousReplicaNum();
+ size_t max_malicious_replica_num =
+ server_config.GetMaxMaliciousReplicaNum();
int checkpoint_water_mark = server_config.GetCheckPointWaterMark();
// Don't read the ledger if first commit time is known
@@ -336,12 +335,12 @@ void CrowService::run() {
res.end("get replica state fail");
};
- for (auto& txn : *resp) {
+ for (auto &txn : *resp) {
BatchUserRequest request;
KVRequest kv_request;
if (request.ParseFromString(txn.second)) {
// transactions
- for (auto& sub_req : request.user_requests()) {
+ for (auto &sub_req : request.user_requests()) {
kv_request.ParseFromString(sub_req.request().data());
std::string kv_request_json = ParseKVRequest(kv_request);
}
@@ -352,11 +351,12 @@ void CrowService::run() {
}
}
- uint64_t epoch_time = std::chrono::duration_cast<std::chrono::seconds>(
- std::chrono::system_clock::now().time_since_epoch()
- ).count();
- uint64_t chain_age = first_commit_time_ == 0 ?
- 0 : epoch_time - first_commit_time_;
+ uint64_t epoch_time =
+ std::chrono::duration_cast<std::chrono::seconds>(
+ std::chrono::system_clock::now().time_since_epoch())
+ .count();
+ uint64_t chain_age =
+ first_commit_time_ == 0 ? 0 : epoch_time - first_commit_time_;
auto block_num_resp = txn_client_.GetBlockNumbers();
if (!block_num_resp.ok()) {
@@ -365,21 +365,23 @@ void CrowService::run() {
}
std::string values = "";
- values.append("[{ \"replicaNum\": " + std::to_string(replica_num)
- + ", \"workerNum\" : " + std::to_string(worker_num)
- + ", \"clientBatchNum\" : " + std::to_string(client_batch_num)
- + ", \"maxProcessTxn\" : " + std::to_string(max_process_txn)
- + ", \"clientBatchWaitTime\" : " + std::to_string(client_batch_wait_time)
- + ", \"inputWorkerNum\" : " + std::to_string(input_worker_num)
- + ", \"outputWorkerNum\" : " + std::to_string(output_worker_num)
- + ", \"clientTimeoutMs\" : " + std::to_string(client_timeout_ms)
- + ", \"minDataReceiveNum\" : " + std::to_string(min_data_receive_num)
- + ", \"maxMaliciousReplicaNum\" : " + std::to_string(max_malicious_replica_num)
- + ", \"checkpointWaterMark\" : " + std::to_string(checkpoint_water_mark)
- + ", \"transactionNum\" : " + std::to_string(num_transactions_)
- + ", \"blockNum\" : " + std::to_string(*block_num_resp)
- + ", \"chainAge\" : " + std::to_string(chain_age)
- + "}]");
+ values.append(
+ "[{ \"replicaNum\": " + std::to_string(replica_num) +
+ ", \"workerNum\" : " + std::to_string(worker_num) +
+ ", \"clientBatchNum\" : " + std::to_string(client_batch_num) +
+ ", \"maxProcessTxn\" : " + std::to_string(max_process_txn) +
+ ", \"clientBatchWaitTime\" : " +
+ std::to_string(client_batch_wait_time) +
+ ", \"inputWorkerNum\" : " + std::to_string(input_worker_num) +
+ ", \"outputWorkerNum\" : " + std::to_string(output_worker_num) +
+ ", \"clientTimeoutMs\" : " + std::to_string(client_timeout_ms) +
+ ", \"minDataReceiveNum\" : " + std::to_string(min_data_receive_num) +
+ ", \"maxMaliciousReplicaNum\" : " +
+ std::to_string(max_malicious_replica_num) +
+ ", \"checkpointWaterMark\" : " + std::to_string(checkpoint_water_mark) +
+ ", \"transactionNum\" : " + std::to_string(num_transactions_) +
+ ", \"blockNum\" : " + std::to_string(*block_num_resp) +
+ ", \"chainAge\" : " + std::to_string(chain_age) + "}]");
LOG(INFO) << std::string(values.c_str());
res.set_header("Content-Type", "application/json");
res.end(std::string(values.c_str()));
@@ -400,10 +402,8 @@ std::string CrowService::GetAllBlocks(int batch_size, bool increment_txn_count,
bool first_batch = true;
while (full_batches) {
std::string cur_batch_str = "";
- if (!first_batch)
- cur_batch_str.append(",\n");
- if (batch_size > 1 && make_sublists)
- cur_batch_str.append("[");
+ if (!first_batch) cur_batch_str.append(",\n");
+ if (batch_size > 1 && make_sublists) cur_batch_str.append("[");
first_batch = false;
int max_seq = min_seq + batch_size - 1;
@@ -423,7 +423,7 @@ std::string CrowService::GetAllBlocks(int batch_size, bool increment_txn_count,
cur_size++;
if (request.ParseFromString(txn.second)) {
if (!first_batch_element) cur_batch_str.append(",");
-
+
first_batch_element = false;
// id
@@ -440,15 +440,14 @@ std::string CrowService::GetAllBlocks(int batch_size, bool increment_txn_count,
kv_request.ParseFromString(sub_req.request().data());
std::string kv_request_json = ParseKVRequest(kv_request);
- if (!first_transaction)
- cur_batch_str.append(",");
+ if (!first_transaction) cur_batch_str.append(",");
first_transaction = false;
cur_batch_str.append(kv_request_json);
cur_batch_str.append("\n");
if (increment_txn_count) num_transactions_++;
}
- cur_batch_str.append("]"); // close transactions list
+ cur_batch_str.append("]"); // close transactions list
// size
cur_batch_str.append(", \"size\": " +
@@ -462,11 +461,9 @@ std::string CrowService::GetAllBlocks(int batch_size, bool increment_txn_count,
cur_batch_str.append("}\n");
}
full_batches = cur_size == batch_size;
- if (batch_size > 1 && make_sublists)
- cur_batch_str.append("]");
+ if (batch_size > 1 && make_sublists) cur_batch_str.append("]");
- if (cur_size > 0)
- values.append(cur_batch_str);
+ if (cur_size > 0) values.append(cur_batch_str);
min_seq += batch_size;
}
@@ -479,25 +476,25 @@ std::string CrowService::GetAllBlocks(int batch_size, bool increment_txn_count,
// Helper function used by the blocks endpoints to create JSON strings
std::string CrowService::ParseKVRequest(const KVRequest &kv_request) {
rapidjson::Document doc;
- if (kv_request.cmd() == 1) { // SET
+ if (kv_request.cmd() == 1) { // SET
doc.SetObject();
rapidjson::Document::AllocatorType &allocator = doc.GetAllocator();
rapidjson::Value val(rapidjson::kObjectType);
doc.AddMember("cmd", "SET", allocator);
doc.AddMember("key", kv_request.key(), allocator);
doc.AddMember("value", kv_request.value(), allocator);
- } else if (kv_request.cmd() == 2) { // GET
+ } else if (kv_request.cmd() == 2) { // GET
doc.SetObject();
rapidjson::Document::AllocatorType &allocator = doc.GetAllocator();
rapidjson::Value val(rapidjson::kObjectType);
doc.AddMember("cmd", "GET", allocator);
doc.AddMember("key", kv_request.key(), allocator);
- } else if (kv_request.cmd() == 3) { // GETALLVALUES
+ } else if (kv_request.cmd() == 3) { // GETALLVALUES
doc.SetObject();
rapidjson::Document::AllocatorType &allocator = doc.GetAllocator();
rapidjson::Value val(rapidjson::kObjectType);
doc.AddMember("cmd", "GETALLVALUES", allocator);
- } else if (kv_request.cmd() == 4) { // GETRANGE
+ } else if (kv_request.cmd() == 4) { // GETRANGE
doc.SetObject();
rapidjson::Document::AllocatorType &allocator = doc.GetAllocator();
rapidjson::Value val(rapidjson::kObjectType);
@@ -514,19 +511,19 @@ std::string CrowService::ParseKVRequest(const KVRequest &kv_request) {
std::string CrowService::ParseCreateTime(uint64_t createtime) {
std::string timestr = "";
- uint64_t sec = createtime / 1000000; // see resilientdb/common/utils/utils.cpp
+ uint64_t sec =
+ createtime / 1000000; // see resilientdb/common/utils/utils.cpp
std::tm *tm_gmt = std::gmtime((time_t *)&sec);
int year = tm_gmt->tm_year + 1900;
- int month = tm_gmt->tm_mon; // 0-indexed
+ int month = tm_gmt->tm_mon; // 0-indexed
int day = tm_gmt->tm_mday;
std::string months[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
// Using date time string format to support the Explorer transaction chart
- if (day < 10)
- timestr += "0";
+ if (day < 10) timestr += "0";
timestr += std::to_string(day) + " " + months[month] + " " +
std::to_string(year) + " ";
@@ -534,16 +531,13 @@ std::string CrowService::ParseCreateTime(uint64_t createtime) {
std::string min_str = std::to_string(tm_gmt->tm_min);
std::string sec_str = std::to_string(tm_gmt->tm_sec);
- if (tm_gmt->tm_hour < 10)
- hour_str = "0" + hour_str;
- if (tm_gmt->tm_min < 10)
- min_str = "0" + min_str;
- if (tm_gmt->tm_sec < 10)
- sec_str = "0" + sec_str;
+ if (tm_gmt->tm_hour < 10) hour_str = "0" + hour_str;
+ if (tm_gmt->tm_min < 10) min_str = "0" + min_str;
+ if (tm_gmt->tm_sec < 10) sec_str = "0" + sec_str;
timestr += hour_str + ":" + min_str + ":" + sec_str + " GMT";
return timestr;
}
-} // namespace sdk
+} // namespace sdk
diff --git a/ecosystem/graphql/service/http_server/crow_service.h b/ecosystem/graphql/service/http_server/crow_service.h
index 9ef34530..162968e2 100644
--- a/ecosystem/graphql/service/http_server/crow_service.h
+++ b/ecosystem/graphql/service/http_server/crow_service.h
@@ -33,14 +33,14 @@
namespace sdk {
class CrowService {
-public:
- CrowService(resdb::ResDBConfig client_config, resdb::ResDBConfig server_config,
- uint16_t port_num = 18000);
+ public:
+ CrowService(resdb::ResDBConfig client_config,
+ resdb::ResDBConfig server_config, uint16_t port_num = 18000);
void run();
-private:
+ private:
std::string GetAllBlocks(int batch_size, bool increment_txn_count = false,
- bool make_sublists=false);
+ bool make_sublists = false);
std::string ParseKVRequest(const KVRequest &kv_request);
std::string ParseCreateTime(uint64_t createtime);
resdb::ResDBConfig client_config_;
@@ -56,4 +56,4 @@ private:
const uint64_t DB_SCAN_TIMEOUT_MS = 30000;
};
-} // namespace sdk
+} // namespace sdk
diff --git a/ecosystem/graphql/service/http_server/crow_service_test.cpp b/ecosystem/graphql/service/http_server/crow_service_test.cpp
index 05d7ac97..c4459a17 100644
--- a/ecosystem/graphql/service/http_server/crow_service_test.cpp
+++ b/ecosystem/graphql/service/http_server/crow_service_test.cpp
@@ -28,7 +28,7 @@ namespace {
using ::testing::Test;
class CrowServiceTest : public Test {
-protected:
+ protected:
crow::SimpleApp app;
};
@@ -91,6 +91,6 @@ TEST_F(CrowServiceTest, GetBlockRange) {
EXPECT_EQ(B, 2);
}
-} // namespace
+} // namespace
-} // namespace resdb
+} // namespace resdb
diff --git a/ecosystem/graphql/service/http_server/example/crow_example.cpp b/ecosystem/graphql/service/http_server/example/crow_example.cpp
index 88a24e0f..afb2df55 100644
--- a/ecosystem/graphql/service/http_server/example/crow_example.cpp
+++ b/ecosystem/graphql/service/http_server/example/crow_example.cpp
@@ -24,7 +24,7 @@
//#include "crow_all.h"
int main() {
- crow::SimpleApp app; // define your crow application
+ crow::SimpleApp app; // define your crow application
// define your endpoint at the root directory
CROW_ROUTE(app, "/")
diff --git a/ecosystem/graphql/service/http_server/example/pistache_example.cpp b/ecosystem/graphql/service/http_server/example/pistache_example.cpp
index e48e1e3a..e220ac87 100644
--- a/ecosystem/graphql/service/http_server/example/pistache_example.cpp
+++ b/ecosystem/graphql/service/http_server/example/pistache_example.cpp
@@ -22,7 +22,7 @@
using namespace Pistache;
class HelloHandler : public Http::Handler {
-public:
+ public:
HTTP_PROTOTYPE(HelloHandler)
void onRequest(const Http::Request &request, Http::ResponseWriter response) {
diff --git a/ecosystem/graphql/service/http_server/sdk_transaction.cpp b/ecosystem/graphql/service/http_server/sdk_transaction.cpp
index 59ccbf5d..f5ca855b 100644
--- a/ecosystem/graphql/service/http_server/sdk_transaction.cpp
+++ b/ecosystem/graphql/service/http_server/sdk_transaction.cpp
@@ -36,4 +36,4 @@ SDKTransaction ParseSDKTransaction(const std::string &json) {
return transaction;
}
-} // namespace resdb
+} // namespace resdb
diff --git a/ecosystem/graphql/service/http_server/sdk_transaction.h b/ecosystem/graphql/service/http_server/sdk_transaction.h
index 37110fab..8ae3dc72 100644
--- a/ecosystem/graphql/service/http_server/sdk_transaction.h
+++ b/ecosystem/graphql/service/http_server/sdk_transaction.h
@@ -29,4 +29,4 @@ struct SDKTransaction {
SDKTransaction ParseSDKTransaction(const std::string &json);
-} // namespace resdb
+} // namespace resdb
diff --git a/ecosystem/graphql/service/kv_service/kv_service_tools.cpp b/ecosystem/graphql/service/kv_service/kv_service_tools.cpp
index b6a9626f..56909170 100644
--- a/ecosystem/graphql/service/kv_service/kv_service_tools.cpp
+++ b/ecosystem/graphql/service/kv_service/kv_service_tools.cpp
@@ -36,8 +36,9 @@ using sdk::ResDBKVClient;
int main(int argc, char **argv) {
if (argc < 3) {
- printf("<config path> <cmd>(set/get/getallvalues/getrange), [key] "
- "[value/key2]\n");
+ printf(
+ "<config path> <cmd>(set/get/getallvalues/getrange), [key] "
+ "[value/key2]\n");
return 0;
}
std::string client_config_file = argv[1];
diff --git a/ecosystem/graphql/service/kv_service/kv_service_transaction_manager.cpp b/ecosystem/graphql/service/kv_service/kv_service_transaction_manager.cpp
index 83af3f5c..6fa59bb4 100644
--- a/ecosystem/graphql/service/kv_service/kv_service_transaction_manager.cpp
+++ b/ecosystem/graphql/service/kv_service/kv_service_transaction_manager.cpp
@@ -41,8 +41,8 @@ KVServiceTransactionManager::KVServiceTransactionManager(
std::unique_ptr<ChainState> state)
: state_(std::move(state)) {}
-std::unique_ptr<std::string>
-KVServiceTransactionManager::ExecuteData(const std::string &request) {
+std::unique_ptr<std::string> KVServiceTransactionManager::ExecuteData(
+ const std::string &request) {
KVRequest kv_request;
KVResponse kv_response;
@@ -93,4 +93,4 @@ std::string KVServiceTransactionManager::GetRange(const std::string &min_key,
return state_->GetRange(min_key, max_key);
}
-} // namespace sdk
+} // namespace sdk
diff --git a/ecosystem/graphql/service/kv_service/kv_service_transaction_manager.h b/ecosystem/graphql/service/kv_service/kv_service_transaction_manager.h
index 368107df..441cfc08 100644
--- a/ecosystem/graphql/service/kv_service/kv_service_transaction_manager.h
+++ b/ecosystem/graphql/service/kv_service/kv_service_transaction_manager.h
@@ -23,30 +23,29 @@
#include <optional>
#include <unordered_map>
-#include "service/kv_service/py_verificator.h"
-
#include "chain/state/chain_state.h"
#include "executor/common/transaction_manager.h"
#include "platform/config/resdb_config_utils.h"
+#include "service/kv_service/py_verificator.h"
namespace sdk {
class KVServiceTransactionManager : public resdb::TransactionManager {
-public:
+ public:
KVServiceTransactionManager(std::unique_ptr<resdb::ChainState> state);
virtual ~KVServiceTransactionManager() = default;
std::unique_ptr<std::string> ExecuteData(const std::string &request) override;
-protected:
+ protected:
virtual void Set(const std::string &key, const std::string &value);
std::string Get(const std::string &key);
std::string GetAllValues();
std::string GetRange(const std::string &min_key, const std::string &max_key);
-private:
+ private:
std::unique_ptr<resdb::ChainState> state_;
std::unique_ptr<PYVerificator> py_verificator_;
};
-} // namespace sdk
+} // namespace sdk
diff --git a/ecosystem/graphql/service/kv_service/py_verificator.cpp b/ecosystem/graphql/service/kv_service/py_verificator.cpp
index 50577c84..5ed6119b 100644
--- a/ecosystem/graphql/service/kv_service/py_verificator.cpp
+++ b/ecosystem/graphql/service/kv_service/py_verificator.cpp
@@ -95,4 +95,4 @@ bool PYVerificator::Validate(const std::string &transaction) {
return locals["is_valid"].cast<bool>();
}
-} // namespace sdk
+} // namespace sdk
diff --git a/ecosystem/graphql/service/kv_service/py_verificator.h b/ecosystem/graphql/service/kv_service/py_verificator.h
index 11679bd2..f6c2d7a8 100644
--- a/ecosystem/graphql/service/kv_service/py_verificator.h
+++ b/ecosystem/graphql/service/kv_service/py_verificator.h
@@ -24,11 +24,11 @@
namespace sdk {
class PYVerificator {
-public:
+ public:
PYVerificator();
~PYVerificator();
bool Validate(const std::string &transaction);
};
-} // namespace sdk
+} // namespace sdk
diff --git a/ecosystem/graphql/service/kv_service/resdb_kv_client.cpp b/ecosystem/graphql/service/kv_service/resdb_kv_client.cpp
index 15edcdd5..9ff55d41 100644
--- a/ecosystem/graphql/service/kv_service/resdb_kv_client.cpp
+++ b/ecosystem/graphql/service/kv_service/resdb_kv_client.cpp
@@ -61,9 +61,8 @@ std::unique_ptr<std::string> ResDBKVClient::GetAllValues() {
return std::make_unique<std::string>(response.value());
}
-std::unique_ptr<std::string>
-ResDBKVClient::GetRange(const std::string &min_key,
- const std::string &max_key) {
+std::unique_ptr<std::string> ResDBKVClient::GetRange(
+ const std::string &min_key, const std::string &max_key) {
KVRequest request;
request.set_cmd(KVRequest::GETRANGE);
request.set_key(min_key);
@@ -77,4 +76,4 @@ ResDBKVClient::GetRange(const std::string &min_key,
return std::make_unique<std::string>(response.value());
}
-} // namespace sdk
+} // namespace sdk
diff --git a/ecosystem/graphql/service/kv_service/resdb_kv_client.h b/ecosystem/graphql/service/kv_service/resdb_kv_client.h
index e08b41a5..aa9ea1ac 100644
--- a/ecosystem/graphql/service/kv_service/resdb_kv_client.h
+++ b/ecosystem/graphql/service/kv_service/resdb_kv_client.h
@@ -25,7 +25,7 @@ namespace sdk {
// ResDBKVClient to send data to the kv server.
class ResDBKVClient : public resdb::TransactionConstructor {
-public:
+ public:
ResDBKVClient(const resdb::ResDBConfig &config);
int Set(const std::string &key, const std::string &data);
@@ -35,4 +35,4 @@ public:
const std::string &max_key);
};
-} // namespace sdk
+} // namespace sdk
diff --git a/ecosystem/graphql/service/pybind_sample/client.cpp b/ecosystem/graphql/service/pybind_sample/client.cpp
index 016a25ae..4b6a978b 100644
--- a/ecosystem/graphql/service/pybind_sample/client.cpp
+++ b/ecosystem/graphql/service/pybind_sample/client.cpp
@@ -17,7 +17,7 @@
* under the License.
*/
-#include <pybind11/embed.h> // everything needed for embedding
+#include <pybind11/embed.h> // everything needed for embedding
#include <fstream>
#include <string>
@@ -25,13 +25,14 @@ namespace py = pybind11;
using namespace py::literals;
int main() {
- py::scoped_interpreter guard{}; // start the interpreter and keep it alive
+ py::scoped_interpreter guard{}; // start the interpreter and keep it alive
printf(
"++++++++++PLEASE MAKE SURE YOU ARE IN THE PYBIND_SAMPLE DIRECTORY WHEN "
"RUNNING THE BINARY+++++++++\n");
- printf("This is so the program correctly finds the Python files in the "
- "pybind_sample directory\n\n");
+ printf(
+ "This is so the program correctly finds the Python files in the "
+ "pybind_sample directory\n\n");
printf("We can read a Python file into a string and execute its entirety\n");
std::ifstream ifs("print_sample.py", std::ifstream::in);
@@ -80,6 +81,5 @@ int main() {
auto is_valid = locals["is_valid"].cast<bool>();
- if (is_valid)
- printf("Valid\n");
+ if (is_valid) printf("Valid\n");
}
diff --git a/executor/common/transaction_manager.cpp b/executor/common/transaction_manager.cpp
index 74df05c9..cd3bd280 100644
--- a/executor/common/transaction_manager.cpp
+++ b/executor/common/transaction_manager.cpp
@@ -62,6 +62,14 @@ std::unique_ptr<std::string> TransactionManager::ExecuteRequest(
return nullptr;
}
+std::vector<std::unique_ptr<std::string>>
+TransactionManager::ExecuteBatchDataWithSeq(
+ uint64_t seq,
+ const std::vector<std::unique_ptr<google::protobuf::Message>>& requests) {
+ seq_ = seq;
+ return ExecuteBatchData(requests);
+}
+
std::vector<std::unique_ptr<std::string>> TransactionManager::ExecuteBatchData(
const std::vector<std::unique_ptr<google::protobuf::Message>>& requests) {
// LOG(ERROR)<<"execute data:"<<requests.size();
@@ -78,6 +86,12 @@ std::vector<std::unique_ptr<std::string>> TransactionManager::ExecuteBatchData(
return ret;
}
+std::unique_ptr<BatchUserResponse> TransactionManager::ExecuteBatchWithSeq(
+ uint64_t seq, const BatchUserRequest& request) {
+ LOG(ERROR) << " execute batch seq:" << seq_;
+ seq_ = seq;
+ return ExecuteBatch(request);
+}
std::unique_ptr<BatchUserResponse> TransactionManager::ExecuteBatch(
const BatchUserRequest& request) {
diff --git a/executor/common/transaction_manager.h b/executor/common/transaction_manager.h
index b1d564ac..45d4c078 100644
--- a/executor/common/transaction_manager.h
+++ b/executor/common/transaction_manager.h
@@ -37,27 +37,38 @@ class TransactionManager {
TransactionManager(bool is_out_of_order = false, bool need_response = true);
virtual ~TransactionManager() = default;
+ std::unique_ptr<BatchUserResponse> ExecuteBatchWithSeq(
+ uint64_t seq, const BatchUserRequest& request);
+
virtual std::unique_ptr<BatchUserResponse> ExecuteBatch(
const BatchUserRequest& request);
std::unique_ptr<std::vector<std::unique_ptr<google::protobuf::Message>>>
Prepare(const BatchUserRequest& request);
+ std::vector<std::unique_ptr<std::string>> ExecuteBatchDataWithSeq(
+ uint64_t seq,
+ const std::vector<std::unique_ptr<google::protobuf::Message>>& requests);
std::vector<std::unique_ptr<std::string>> ExecuteBatchData(
const std::vector<std::unique_ptr<google::protobuf::Message>>& requests);
+
virtual std::unique_ptr<std::string> ExecuteData(const std::string& request);
bool IsOutOfOrder();
bool NeedResponse();
- virtual Storage* GetStorage() { return nullptr; };
+ virtual Storage* GetStorage() { return storage_ ? storage_.get() : nullptr; }
protected:
virtual std::unique_ptr<google::protobuf::Message> ParseData(
const std::string& data);
virtual std::unique_ptr<std::string> ExecuteRequest(
const google::protobuf::Message& request);
+ uint64_t seq_ = 0;
+
+ std::unique_ptr<Storage> storage_;
+
private:
bool is_out_of_order_ = false;
bool need_response_ = true;
diff --git a/executor/contract/executor/contract_executor.cpp b/executor/contract/executor/contract_executor.cpp
index 99f6f205..62a46981 100644
--- a/executor/contract/executor/contract_executor.cpp
+++ b/executor/contract/executor/contract_executor.cpp
@@ -24,7 +24,7 @@
namespace resdb {
namespace contract {
-ContractTransactionManager::ContractTransactionManager(Storage * storage)
+ContractTransactionManager::ContractTransactionManager(Storage* storage)
: contract_manager_(std::make_unique<ContractManager>(storage)),
address_manager_(std::make_unique<AddressManager>()) {}
@@ -42,7 +42,7 @@ std::unique_ptr<std::string> ContractTransactionManager::ExecuteData(
absl::StatusOr<Account> account_or = CreateAccount();
if (account_or.ok()) {
response.mutable_account()->Swap(&(*account_or));
- LOG(ERROR)<<" create count:"<<response.account().DebugString();
+ LOG(ERROR) << " create count:" << response.account().DebugString();
} else {
ret = -1;
}
@@ -134,24 +134,17 @@ absl::StatusOr<std::string> ContractTransactionManager::Execute(
absl::StatusOr<std::string> ContractTransactionManager::GetBalance(
const Request& request) {
-
- Address account =
- AddressManager::HexToAddress(request.account());
+ Address account = AddressManager::HexToAddress(request.account());
return contract_manager_->GetBalance(account);
}
absl::StatusOr<std::string> ContractTransactionManager::SetBalance(
const Request& request) {
-
- Address account =
- AddressManager::HexToAddress(request.account());
- Address balance =
- AddressManager::HexToAddress(request.balance());
+ Address account = AddressManager::HexToAddress(request.account());
+ Address balance = AddressManager::HexToAddress(request.balance());
int ret = contract_manager_->SetBalance(account, balance);
return std::to_string(ret);
}
-
-
} // namespace contract
} // namespace resdb
diff --git a/executor/contract/executor/contract_executor.h b/executor/contract/executor/contract_executor.h
index 489f822f..d8d5f7e4 100644
--- a/executor/contract/executor/contract_executor.h
+++ b/executor/contract/executor/contract_executor.h
@@ -31,7 +31,7 @@ namespace contract {
class ContractTransactionManager : public TransactionManager {
public:
- ContractTransactionManager(Storage * storage);
+ ContractTransactionManager(Storage* storage);
virtual ~ContractTransactionManager() = default;
std::unique_ptr<std::string> ExecuteData(const std::string& request) override;
diff --git a/executor/contract/executor/contract_executor_test.cpp b/executor/contract/executor/contract_executor_test.cpp
index 8f7d44de..7874675e 100644
--- a/executor/contract/executor/contract_executor_test.cpp
+++ b/executor/contract/executor/contract_executor_test.cpp
@@ -19,19 +19,19 @@
#include "executor/contract/executor/contract_executor.h"
-#include "chain/storage/memory_db.h"
-
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <fstream>
+#include "chain/storage/memory_db.h"
+
namespace resdb {
namespace contract {
namespace {
-using ::testing::Test;
using resdb::storage::MemoryDB;
+using ::testing::Test;
const std::string test_dir = std::string(getenv("TEST_SRCDIR")) + "/" +
std::string(getenv("TEST_WORKSPACE")) +
@@ -45,7 +45,7 @@ std::string ToString(const Request& request) {
class ContractTransactionManagerTest : public Test {
public:
- ContractTransactionManagerTest() : executor_(&db_) {
+ ContractTransactionManagerTest() : executor_(&db_) {
std::string contract_path = test_dir + "test_data/contract.json";
contract_name_ = "token.sol:Token";
@@ -132,7 +132,8 @@ class ContractTransactionManagerTest : public Test {
}
}
- absl::StatusOr<std::string> SetBalance(const std::string& account_address, const std::string& balance) {
+ absl::StatusOr<std::string> SetBalance(const std::string& account_address,
+ const std::string& balance) {
Request request;
Response response;
@@ -377,7 +378,7 @@ TEST_F(ContractTransactionManagerTest, GetFromKV) {
{
auto result = GetBalance(account.address());
- EXPECT_EQ(*result, 600);
+ EXPECT_EQ(*result, 600);
}
}
@@ -398,7 +399,6 @@ TEST_F(ContractTransactionManagerTest, GetFromKV) {
}
{
-
{
auto result = SetBalance(account.address(), "1000");
EXPECT_EQ(*result, "1");
@@ -454,8 +454,8 @@ TEST_F(ContractTransactionManagerTest, GetFromKV2) {
EXPECT_EQ(*result, 0x3e8);
}
- //Account transfer_receiver = CreateAccount();
- //EXPECT_FALSE(account.address().empty());
+ // Account transfer_receiver = CreateAccount();
+ // EXPECT_FALSE(account.address().empty());
// receiver 0
{
Params func_params;
@@ -491,7 +491,7 @@ TEST_F(ContractTransactionManagerTest, GetFromKV2) {
{
auto result = GetBalance(account.address());
- EXPECT_EQ(*result, 600);
+ EXPECT_EQ(*result, 600);
}
}
@@ -510,11 +510,8 @@ TEST_F(ContractTransactionManagerTest, GetFromKV2) {
EXPECT_EQ(*result, 400);
}
}
-
}
-
-
} // namespace
} // namespace contract
} // namespace resdb
diff --git a/executor/contract/manager/BUILD b/executor/contract/manager/BUILD
index ee570c37..6ba19cc5 100644
--- a/executor/contract/manager/BUILD
+++ b/executor/contract/manager/BUILD
@@ -32,8 +32,8 @@ cc_library(
hdrs = ["contract_manager.h"],
deps = [
":address_manager",
- ":utils",
":global_state",
+ ":utils",
"//common:comm",
"//proto/contract:func_params_cc_proto",
],
@@ -78,12 +78,11 @@ cc_library(
hdrs = ["global_view.h"],
deps = [
":utils",
- "//chain/storage:storage",
+ "//chain/storage",
"//common:comm",
],
)
-
cc_library(
name = "evm_state",
hdrs = ["evm_state.h"],
@@ -93,7 +92,6 @@ cc_library(
],
)
-
cc_library(
name = "global_state",
srcs = ["global_state.cpp"],
@@ -104,4 +102,3 @@ cc_library(
"//common:comm",
],
)
-
diff --git a/executor/contract/manager/contract_manager.cpp b/executor/contract/manager/contract_manager.cpp
index 862fc7e5..e2515a3c 100644
--- a/executor/contract/manager/contract_manager.cpp
+++ b/executor/contract/manager/contract_manager.cpp
@@ -148,7 +148,8 @@ std::string ContractManager::GetBalance(const Address& account) {
return gs_->GetBalance(account);
}
-int ContractManager::SetBalance(const Address& account, const uint256_t& balance) {
+int ContractManager::SetBalance(const Address& account,
+ const uint256_t& balance) {
return gs_->SetBalance(account, balance);
}
diff --git a/executor/contract/manager/contract_manager.h b/executor/contract/manager/contract_manager.h
index d5347fae..410544fa 100644
--- a/executor/contract/manager/contract_manager.h
+++ b/executor/contract/manager/contract_manager.h
@@ -20,11 +20,11 @@
#pragma once
#include "absl/status/statusor.h"
+#include "chain/storage/storage.h"
#include "eEVM/opcode.h"
#include "eEVM/simple/simpleglobalstate.h"
-#include "chain/storage/storage.h"
-#include "executor/contract/manager/utils.h"
#include "executor/contract/manager/global_state.h"
+#include "executor/contract/manager/utils.h"
#include "proto/contract/func_params.pb.h"
namespace resdb {
diff --git a/executor/contract/manager/contract_manager_test.cpp b/executor/contract/manager/contract_manager_test.cpp
index db36d188..604e35ac 100644
--- a/executor/contract/manager/contract_manager_test.cpp
+++ b/executor/contract/manager/contract_manager_test.cpp
@@ -24,15 +24,15 @@
#include <fstream>
-#include "executor/contract/manager/address_manager.h"
#include "chain/storage/memory_db.h"
+#include "executor/contract/manager/address_manager.h"
namespace resdb {
namespace contract {
namespace {
-using ::testing::Test;
using resdb::storage::MemoryDB;
+using ::testing::Test;
const std::string test_dir = std::string(getenv("TEST_SRCDIR")) + "/" +
std::string(getenv("TEST_WORKSPACE")) +
diff --git a/executor/contract/manager/evm_state.h b/executor/contract/manager/evm_state.h
index 26fe199e..c792c0eb 100644
--- a/executor/contract/manager/evm_state.h
+++ b/executor/contract/manager/evm_state.h
@@ -17,7 +17,6 @@
* under the License.
*/
-
#pragma once
#include "eEVM/globalstate.h"
diff --git a/executor/contract/manager/global_state.cpp b/executor/contract/manager/global_state.cpp
index 39648ca6..05084edd 100644
--- a/executor/contract/manager/global_state.cpp
+++ b/executor/contract/manager/global_state.cpp
@@ -17,7 +17,6 @@
* under the License.
*/
-
#include "executor/contract/manager/global_state.h"
#include <glog/logging.h>
@@ -30,16 +29,15 @@ using eevm::Address;
using eevm::Code;
using eevm::SimpleAccount;
-
uint256_t AccountToAddress(const eevm::Address& account) {
- std::vector<uint8_t> code;
- code.resize(64);
- std::fill(code.begin(), code.end(), 0);
- eevm::to_big_endian(account, code.data());
-
- uint8_t h[32];
- eevm::keccak_256(code.data(), static_cast<unsigned int>(64), h);
- return eevm::from_big_endian(h, sizeof(h));
+ std::vector<uint8_t> code;
+ code.resize(64);
+ std::fill(code.begin(), code.end(), 0);
+ eevm::to_big_endian(account, code.data());
+
+ uint8_t h[32];
+ eevm::keccak_256(code.data(), static_cast<unsigned int>(64), h);
+ return eevm::from_big_endian(h, sizeof(h));
}
GlobalState::GlobalState(resdb::Storage* storage) : storage_(storage) {}
@@ -76,12 +74,15 @@ void GlobalState::Insert(const StateEntry& p) {
}
std::string GlobalState::GetBalance(const eevm::Address& account) {
- std::string key = "contract_balance_" + eevm::to_hex_string(AccountToAddress(account));
+ std::string key =
+ "contract_balance_" + eevm::to_hex_string(AccountToAddress(account));
return storage_->GetValue(key);
}
-int GlobalState::SetBalance(const eevm::Address& account, const uint256_t& balance) {
- std::string key = "contract_balance_" + eevm::to_hex_string(AccountToAddress(account));
+int GlobalState::SetBalance(const eevm::Address& account,
+ const uint256_t& balance) {
+ std::string key =
+ "contract_balance_" + eevm::to_hex_string(AccountToAddress(account));
return storage_->SetValue(key, eevm::to_hex_string(balance));
}
diff --git a/executor/contract/manager/global_state.h b/executor/contract/manager/global_state.h
index 0320e35e..76f265dd 100644
--- a/executor/contract/manager/global_state.h
+++ b/executor/contract/manager/global_state.h
@@ -17,7 +17,6 @@
* under the License.
*/
-
#pragma once
#include "eEVM/simple/simpleaccount.h"
diff --git a/executor/contract/manager/global_view.cpp b/executor/contract/manager/global_view.cpp
index 0fbbbef2..d6f29e4a 100644
--- a/executor/contract/manager/global_view.cpp
+++ b/executor/contract/manager/global_view.cpp
@@ -17,7 +17,6 @@
* under the License.
*/
-
#include "executor/contract/manager/global_view.h"
#include <glog/logging.h>
diff --git a/executor/contract/manager/global_view.h b/executor/contract/manager/global_view.h
index 6fdfc583..b7381ac5 100644
--- a/executor/contract/manager/global_view.h
+++ b/executor/contract/manager/global_view.h
@@ -21,8 +21,8 @@
#include <map>
-#include "eEVM/storage.h"
#include "chain/storage/storage.h"
+#include "eEVM/storage.h"
namespace resdb {
namespace contract {
diff --git a/executor/kv/BUILD b/executor/kv/BUILD
index d8a47bcf..89bb67c7 100644
--- a/executor/kv/BUILD
+++ b/executor/kv/BUILD
@@ -28,9 +28,9 @@ cc_library(
"//chain/storage",
"//common:comm",
"//executor/common:transaction_manager",
+ "//executor/contract/executor:contract_executor",
"//platform/config:resdb_config_utils",
"//proto/kv:kv_cc_proto",
- "//executor/contract/executor:contract_executor",
],
)
diff --git a/executor/kv/kv_executor.cpp b/executor/kv/kv_executor.cpp
index c587f592..719093a4 100644
--- a/executor/kv/kv_executor.cpp
+++ b/executor/kv/kv_executor.cpp
@@ -18,15 +18,18 @@
*/
#include "executor/kv/kv_executor.h"
-#include "executor/contract/executor/contract_executor.h"
#include <glog/logging.h>
+#include "executor/contract/executor/contract_executor.h"
+
namespace resdb {
-KVExecutor::KVExecutor(std::unique_ptr<Storage> storage)
- : storage_(std::move(storage)) {
- contract_manager_ = std::make_unique<resdb::contract::ContractTransactionManager>(storage_.get());
+KVExecutor::KVExecutor(std::unique_ptr<Storage> storage) {
+ storage_ = std::move(storage);
+ contract_manager_ =
+ std::make_unique<resdb::contract::ContractTransactionManager>(
+ storage_.get());
}
std::unique_ptr<google::protobuf::Message> KVExecutor::ParseData(
@@ -68,10 +71,10 @@ std::unique_ptr<std::string> KVExecutor::ExecuteRequest(
} else if (kv_request.cmd() == KVRequest::GET_TOP) {
GetTopHistory(kv_request.key(), kv_request.top_number(),
kv_response.mutable_items());
- }
- else if(!kv_request.smart_contract_request().empty()){
- std::unique_ptr<std::string> resp = contract_manager_->ExecuteData(kv_request.smart_contract_request());
- if(resp != nullptr){
+ } else if (!kv_request.smart_contract_request().empty()) {
+ std::unique_ptr<std::string> resp =
+ contract_manager_->ExecuteData(kv_request.smart_contract_request());
+ if (resp != nullptr) {
kv_response.set_smart_contract_response(*resp);
}
}
@@ -94,7 +97,6 @@ std::unique_ptr<std::string> KVExecutor::ExecuteData(
return nullptr;
}
- LOG(ERROR)<<" execute cmd:"<<kv_request.cmd();
if (kv_request.cmd() == KVRequest::SET) {
Set(kv_request.key(), kv_request.value());
} else if (kv_request.cmd() == KVRequest::GET) {
@@ -119,10 +121,10 @@ std::unique_ptr<std::string> KVExecutor::ExecuteData(
} else if (kv_request.cmd() == KVRequest::GET_TOP) {
GetTopHistory(kv_request.key(), kv_request.top_number(),
kv_response.mutable_items());
- }
- else if(!kv_request.smart_contract_request().empty()){
- std::unique_ptr<std::string> resp = contract_manager_->ExecuteData(kv_request.smart_contract_request());
- if(resp != nullptr){
+ } else if (!kv_request.smart_contract_request().empty()) {
+ std::unique_ptr<std::string> resp =
+ contract_manager_->ExecuteData(kv_request.smart_contract_request());
+ if (resp != nullptr) {
kv_response.set_smart_contract_response(*resp);
}
}
@@ -135,16 +137,14 @@ std::unique_ptr<std::string> KVExecutor::ExecuteData(
}
void KVExecutor::Set(const std::string& key, const std::string& value) {
- LOG(ERROR)<<" set key:"<<key;
- storage_->SetValue(key, value);
+ storage_->SetValueWithSeq(key, value, seq_);
}
std::string KVExecutor::Get(const std::string& key) {
- LOG(ERROR)<<" get key:"<<key;
- return storage_->GetValue(key);
+ return storage_->GetValueWithSeq(key, 0).first;
}
-std::string KVExecutor::GetAllValues() { return storage_->GetAllValues(); }
+std::string KVExecutor::GetAllValues() { return ""; }
// Get values on a range of keys
std::string KVExecutor::GetRange(const std::string& min_key,
@@ -164,16 +164,7 @@ void KVExecutor::GetWithVersion(const std::string& key, int version,
info->set_version(ret.second);
}
-void KVExecutor::GetAllItems(Items* items) {
- const std::map<std::string, std::pair<std::string, int>>& ret =
- storage_->GetAllItems();
- for (auto it : ret) {
- Item* item = items->add_item();
- item->set_key(it.first);
- item->mutable_value_info()->set_value(it.second.first);
- item->mutable_value_info()->set_version(it.second.second);
- }
-}
+void KVExecutor::GetAllItems(Items* items) { return; }
void KVExecutor::GetKeyRange(const std::string& min_key,
const std::string& max_key, Items* items) {
diff --git a/executor/kv/kv_executor.h b/executor/kv/kv_executor.h
index fef12597..229dc837 100644
--- a/executor/kv/kv_executor.h
+++ b/executor/kv/kv_executor.h
@@ -40,6 +40,7 @@ class KVExecutor : public TransactionManager {
const std::string& request) override;
std::unique_ptr<std::string> ExecuteRequest(
const google::protobuf::Message& kv_request) override;
+
protected:
virtual void Set(const std::string& key, const std::string& value);
std::string Get(const std::string& key);
@@ -57,8 +58,6 @@ class KVExecutor : public TransactionManager {
void GetTopHistory(const std::string& key, int top_number, Items* items);
private:
- std::unique_ptr<Storage> storage_;
-
std::unique_ptr<TransactionManager> contract_manager_;
};
diff --git a/interface/kv/contract_client.cpp b/interface/kv/contract_client.cpp
index 26259eb9..6f284011 100644
--- a/interface/kv/contract_client.cpp
+++ b/interface/kv/contract_client.cpp
@@ -117,9 +117,9 @@ absl::StatusOr<std::string> ContractClient::ExecuteContract(
}
return response.res();
}
-
-absl::StatusOr<std::string> ContractClient::GetBalance(const std::string& address) {
+absl::StatusOr<std::string> ContractClient::GetBalance(
+ const std::string& address) {
Request request;
Response response;
request.set_account(address);
@@ -133,7 +133,8 @@ absl::StatusOr<std::string> ContractClient::GetBalance(const std::string& addres
return response.res();
}
-absl::StatusOr<std::string> ContractClient::SetBalance(const std::string& address, const std::string& balance) {
+absl::StatusOr<std::string> ContractClient::SetBalance(
+ const std::string& address, const std::string& balance) {
Request request;
Response response;
request.set_account(address);
@@ -148,7 +149,8 @@ absl::StatusOr<std::string> ContractClient::SetBalance(const std::string& addres
return response.res();
}
-int ContractClient::SendRequestInternal(const Request& request, Response * response) {
+int ContractClient::SendRequestInternal(const Request& request,
+ Response* response) {
KVRequest kv_request;
request.SerializeToString(kv_request.mutable_smart_contract_request());
KVResponse kv_response;
@@ -158,12 +160,10 @@ int ContractClient::SendRequestInternal(const Request& request, Response * respo
return ret;
}
printf("get response from sm\n");
-
+
response->ParseFromString(kv_response.smart_contract_response());
return 0;
}
-
-
} // namespace contract
} // namespace resdb
diff --git a/interface/kv/contract_client.h b/interface/kv/contract_client.h
index 7df166ef..e0043c68 100644
--- a/interface/kv/contract_client.h
+++ b/interface/kv/contract_client.h
@@ -44,10 +44,12 @@ class ContractClient : public TransactionConstructor {
const std::vector<std::string>& func_params);
absl::StatusOr<std::string> GetBalance(const std::string& address);
- absl::StatusOr<std::string> SetBalance(const std::string& address, const std::string& balance);
+ absl::StatusOr<std::string> SetBalance(const std::string& address,
+ const std::string& balance);
- private:
- int SendRequestInternal(const resdb::contract::Request& request, resdb::contract::Response* response);
+ private:
+ int SendRequestInternal(const resdb::contract::Request& request,
+ resdb::contract::Response* response);
};
} // namespace contract
diff --git a/platform/config/BUILD b/platform/config/BUILD
index 0611ac41..3f46dfeb 100644
--- a/platform/config/BUILD
+++ b/platform/config/BUILD
@@ -28,7 +28,6 @@ cc_library(
],
)
-
#filegroup(
# name = "data_files",
# srcs = ["test.config", "expect_test.config"],
@@ -44,15 +43,15 @@ cc_library(
cc_test(
name = "resdb_config_test",
srcs = ["resdb_config_test.cpp"],
+ data = [
+ "//platform/config:expect_test.config",
+ "//platform/config:test.config",
+ ],
deps = [
":resdb_config",
- "//common/test:test_main",
":resdb_config_utils",
+ "//common/test:test_main",
],
- data = [
- "//platform/config:test.config",
- "//platform/config:expect_test.config",
- ]
)
cc_library(
diff --git a/platform/config/resdb_config.h b/platform/config/resdb_config.h
index 9867c6d5..876dad85 100644
--- a/platform/config/resdb_config.h
+++ b/platform/config/resdb_config.h
@@ -139,7 +139,6 @@ class ResDBConfig {
uint64_t viewchange_commit_timeout_ms_ =
60000; // default 60s to change viewchange
-
// This is the default settings.
// change these parameters in the configuration.
uint32_t max_process_txn_ = 64;
diff --git a/platform/config/resdb_config_test.cpp b/platform/config/resdb_config_test.cpp
index 046fae98..844c22ce 100644
--- a/platform/config/resdb_config_test.cpp
+++ b/platform/config/resdb_config_test.cpp
@@ -21,13 +21,13 @@
#include <google/protobuf/util/message_differencer.h>
#include <gtest/gtest.h>
-#include <filesystem>
+#include <filesystem>
#include <thread>
-#include "resdb_config_utils.h"
#include "common/test/test_macros.h"
#include "gmock/gmock.h"
+#include "resdb_config_utils.h"
namespace resdb {
namespace {
@@ -126,16 +126,15 @@ TEST(ResDBConfigTest, ResDBConfigWith2Replicas) {
*/
TEST(ResDBConfigTest, ResDBConfigFromFile) {
- const char * file = "platform/config/test.config";
- const char * ext_file = "platform/config/expect_test.config";
+ const char* file = "platform/config/test.config";
+ const char* ext_file = "platform/config/expect_test.config";
ResConfigData config_data = ReadConfigFromFile(file);
ResConfigData ext_config_data = ReadConfigFromFile(ext_file);
- std::cout<<config_data.DebugString()<<std::endl;
+ std::cout << config_data.DebugString() << std::endl;
EXPECT_THAT(config_data, EqualsProto(ext_config_data));
}
-
} // namespace
} // namespace resdb
diff --git a/platform/config/resdb_config_utils.cpp b/platform/config/resdb_config_utils.cpp
index b4f4c4af..daf83a76 100644
--- a/platform/config/resdb_config_utils.cpp
+++ b/platform/config/resdb_config_utils.cpp
@@ -25,10 +25,10 @@
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
-#include <regex>
-#include <nlohmann/json.hpp>
#include <fstream>
+#include <nlohmann/json.hpp>
+#include <regex>
namespace resdb {
@@ -94,23 +94,24 @@ ReplicaInfo GenerateReplicaInfo(int id, const std::string& ip, int port) {
}
std::string RemoveJsonComments(const std::string& jsonWithComments) {
- std::string result = std::regex_replace(jsonWithComments, std::regex("/\\*.*?\\*/"), "");
- result = std::regex_replace(result, std::regex("//.*?\\n"), "\n");
- return result;
+ std::string result =
+ std::regex_replace(jsonWithComments, std::regex("/\\*.*?\\*/"), "");
+ result = std::regex_replace(result, std::regex("//.*?\\n"), "\n");
+ return result;
}
-
ResConfigData ReadConfigFromFile(const std::string& file_name) {
std::stringstream json_data;
std::ifstream infile(file_name.c_str());
if (!infile.is_open()) {
- std::cerr << "Failed to open file." <<file_name<<" "<< strerror(errno)<<std::endl;
+ std::cerr << "Failed to open file." << file_name << " " << strerror(errno)
+ << std::endl;
return ResConfigData();
}
json_data << infile.rdbuf();
std::string cleanJson = RemoveJsonComments(json_data.str());
-
+
ResConfigData config_data;
JsonParseOptions options;
auto status = JsonStringToMessage(cleanJson, &config_data, options);
@@ -129,10 +130,10 @@ std::vector<ReplicaInfo> ReadConfig(const std::string& file_name) {
std::string ip;
int port;
while (infile >> id >> ip >> port) {
- if(id == 0) {
+ if (id == 0) {
continue;
}
- if(ip.size()==0) {
+ if (ip.size() == 0) {
continue;
}
replicas.push_back(GenerateReplicaInfo(id, ip, port));
diff --git a/platform/config/resdb_config_utils.h b/platform/config/resdb_config_utils.h
index 1251e64d..56c3fa63 100644
--- a/platform/config/resdb_config_utils.h
+++ b/platform/config/resdb_config_utils.h
@@ -41,8 +41,6 @@ std::unique_ptr<ResDBConfig> GenerateResDBConfig(
ResDBConfig GenerateResDBConfig(const std::string& config_file);
-
ResConfigData ReadConfigFromFile(const std::string& file_name);
} // namespace resdb
-
diff --git a/platform/consensus/checkpoint/checkpoint.h b/platform/consensus/checkpoint/checkpoint.h
index 7a5b967c..f21b7ff0 100644
--- a/platform/consensus/checkpoint/checkpoint.h
+++ b/platform/consensus/checkpoint/checkpoint.h
@@ -27,6 +27,7 @@ class CheckPoint {
virtual ~CheckPoint() = default;
virtual uint64_t GetStableCheckpoint() = 0;
+ // virtual uint64_t GetLastExecutedSeq() = 0;
};
} // namespace resdb
diff --git a/platform/consensus/checkpoint/mock_checkpoint.h b/platform/consensus/checkpoint/mock_checkpoint.h
index 837d895c..4db24f6d 100644
--- a/platform/consensus/checkpoint/mock_checkpoint.h
+++ b/platform/consensus/checkpoint/mock_checkpoint.h
@@ -28,6 +28,7 @@ namespace resdb {
class MockCheckPoint : public CheckPoint {
public:
MOCK_METHOD(uint64_t, GetStableCheckpoint, (), (override));
+ // MOCK_METHOD(uint64_t, GetLastExecutedSeq, (), (override));
};
} // namespace resdb
diff --git a/platform/consensus/execution/transaction_executor.cpp b/platform/consensus/execution/transaction_executor.cpp
index a62e55f5..0a7401bc 100644
--- a/platform/consensus/execution/transaction_executor.cpp
+++ b/platform/consensus/execution/transaction_executor.cpp
@@ -20,6 +20,7 @@
#include "platform/consensus/execution/transaction_executor.h"
#include <glog/logging.h>
+
#include "common/utils/utils.h"
namespace resdb {
@@ -36,7 +37,6 @@ TransactionExecutor::TransactionExecutor(
execute_queue_("execute"),
stop_(false),
duplicate_manager_(nullptr) {
-
memset(blucket_, 0, sizeof(blucket_));
global_stats_ = Stats::GetGlobalStats();
ordering_thread_ = std::thread(&TransactionExecutor::OrderMessage, this);
@@ -72,7 +72,8 @@ void TransactionExecutor::RegisterExecute(int64_t seq) {
void TransactionExecutor::WaitForExecute(int64_t seq) {
if (execute_thread_num_ == 1) return;
int pre_idx = (seq - 1 + blucket_num_) % blucket_num_;
-
+ // LOG(ERROR)<<"wait for:"<<seq<<" pre idx:"<<pre_idx<<"
+ // thread:"<<execute_thread_num_;
while (!IsStop()) {
std::unique_lock<std::mutex> lk(mutex_);
cv_.wait_for(lk, std::chrono::milliseconds(10000), [&] {
@@ -89,7 +90,7 @@ void TransactionExecutor::FinishExecute(int64_t seq) {
if (execute_thread_num_ == 1) return;
int idx = seq % blucket_num_;
std::unique_lock<std::mutex> lk(mutex_);
- // LOG(ERROR)<<"finish :"<<seq<<" done";
+ // LOG(ERROR)<<"finish :"<<seq<<" done"<<" idx:"<<idx;
blucket_[idx] = 3;
cv_.notify_all();
}
@@ -115,6 +116,7 @@ void TransactionExecutor::Stop() {
}
Storage* TransactionExecutor::GetStorage() {
+ assert(transaction_manager_);
return transaction_manager_ ? transaction_manager_->GetStorage() : nullptr;
}
@@ -132,6 +134,11 @@ uint64_t TransactionExecutor::GetMaxPendingExecutedSeq() {
return next_execute_seq_ - 1;
}
+void TransactionExecutor::SetPendingExecutedSeq(int seq) {
+ // LOG(ERROR)<<" seq next pending seq:"<<seq;
+ next_execute_seq_ = seq;
+}
+
bool TransactionExecutor::NeedResponse() {
return transaction_manager_ == nullptr ||
transaction_manager_->NeedResponse();
@@ -174,8 +181,8 @@ void TransactionExecutor::OrderMessage() {
global_stats_->IncExecute();
uint64_t seq = message->seq();
if (next_execute_seq_ > seq) {
- // LOG(INFO) << "request seq:" << seq << " has been executed"
- // << " next seq:" << next_execute_seq_;
+ LOG(INFO) << "request seq:" << seq << " has been executed"
+ << " next seq:" << next_execute_seq_;
continue;
}
@@ -198,20 +205,25 @@ void TransactionExecutor::OrderMessage() {
}
void TransactionExecutor::AddExecuteMessage(std::unique_ptr<Request> message) {
- global_stats_->IncCommit();
- message->set_commit_time(GetCurrentTime());
- execute_queue_.Push(std::move(message));
+ global_stats_->IncCommit();
+ message->set_commit_time(GetCurrentTime());
+ execute_queue_.Push(std::move(message));
}
void TransactionExecutor::ExecuteMessage() {
while (!IsStop()) {
- auto message = execute_queue_.Pop();
- if (message == nullptr) {
- continue;
- }
+ std::unique_ptr<Request> message = nullptr;
bool need_execute = true;
- if (transaction_manager_ && transaction_manager_->IsOutOfOrder()) {
- need_execute = false;
+ {
+ std::unique_lock<std::mutex> lk(e_mutex_);
+ message = execute_queue_.Pop();
+ if (message == nullptr) {
+ continue;
+ }
+ if (transaction_manager_ && transaction_manager_->IsOutOfOrder()) {
+ need_execute = false;
+ }
+ RegisterExecute(message->seq());
}
Execute(std::move(message), need_execute);
}
@@ -244,9 +256,10 @@ void TransactionExecutor::OnlyExecute(std::unique_ptr<Request> request) {
// << batch_request.user_requests_size()<<" proxy
// id:"<<request->proxy_id();
std::unique_ptr<BatchUserResponse> response;
- global_stats_->GetTransactionDetails(batch_request);
+ global_stats_->GetTransactionDetails(batch_request);
if (transaction_manager_) {
- response = transaction_manager_->ExecuteBatch(batch_request);
+ response = transaction_manager_->ExecuteBatchWithSeq(request->seq(),
+ batch_request);
}
// global_stats_->IncTotalRequest(batch_request.user_requests_size());
@@ -255,10 +268,9 @@ void TransactionExecutor::OnlyExecute(std::unique_ptr<Request> request) {
void TransactionExecutor::Execute(std::unique_ptr<Request> request,
bool need_execute) {
- RegisterExecute(request->seq());
std::unique_ptr<BatchUserRequest> batch_request = nullptr;
std::unique_ptr<std::vector<std::unique_ptr<google::protobuf::Message>>> data;
- std::vector<std::unique_ptr<google::protobuf::Message>> * data_p = nullptr;
+ std::vector<std::unique_ptr<google::protobuf::Message>>* data_p = nullptr;
BatchUserRequest* batch_request_p = nullptr;
// Execute the request, then send the response back to the user.
@@ -276,26 +288,28 @@ void TransactionExecutor::Execute(std::unique_ptr<Request> request,
batch_request_p = batch_request.get();
// LOG(ERROR)<<"get data from req:";
} else {
- assert(batch_request_p);
+ assert(batch_request_p);
batch_request_p->set_seq(request->seq());
batch_request_p->set_proxy_id(request->proxy_id());
// LOG(ERROR)<<" get from cache:"<<uid;
}
assert(batch_request_p);
- // LOG(INFO) << " get request batch size:"
- // << batch_request.user_requests_size()<<" proxy id:"
- // <<request->proxy_id()<<" need execute:"<<need_execute;
+ // LOG(ERROR) << " get request batch size:"
+ // << batch_request_p->user_requests_size()<<" proxy id:"
+ // <<request->proxy_id()<<" need execute:"<<need_execute<<"
+ // seq:"<<request->seq();
std::unique_ptr<BatchUserResponse> response;
global_stats_->GetTransactionDetails(*batch_request_p);
if (transaction_manager_ && need_execute) {
if (execute_thread_num_ == 1) {
- response = transaction_manager_->ExecuteBatch(*batch_request_p);
+ response = transaction_manager_->ExecuteBatchWithSeq(request->seq(),
+ *batch_request_p);
} else {
std::vector<std::unique_ptr<std::string>> response_v;
- if(data_p == nullptr) {
+ if (data_p == nullptr) {
int64_t start_time = GetCurrentTime();
data = std::move(transaction_manager_->Prepare(*batch_request_p));
int64_t end_time = GetCurrentTime();
@@ -307,26 +321,34 @@ void TransactionExecutor::Execute(std::unique_ptr<Request> request,
}
WaitForExecute(request->seq());
- if(data_p->empty() || (*data_p)[0] == nullptr){
- response = transaction_manager_->ExecuteBatch(*batch_request_p);
- }
- else {
- response_v = transaction_manager_->ExecuteBatchData(*data_p);
- }
+ if (last_seq_ == 0) {
+ last_seq_ = request->seq();
+ } else {
+ assert(last_seq_ + 1 == request->seq());
+ last_seq_++;
+ }
+ if (data_p->empty() || (*data_p)[0] == nullptr) {
+ response = transaction_manager_->ExecuteBatchWithSeq(request->seq(),
+ *batch_request_p);
+ } else {
+ response_v = transaction_manager_->ExecuteBatchDataWithSeq(
+ request->seq(), *data_p);
+ }
FinishExecute(request->seq());
- if(response == nullptr){
- response = std::make_unique<BatchUserResponse>();
- for (auto& s : response_v) {
- response->add_response()->swap(*s);
- }
+ if (response == nullptr) {
+ response = std::make_unique<BatchUserResponse>();
+ for (auto& s : response_v) {
+ response->add_response()->swap(*s);
+ }
}
}
}
// LOG(ERROR)<<" CF = :"<<(cf==1)<<" uid:"<<uid;
- if (duplicate_manager_ && batch_request_p) {
- duplicate_manager_->AddExecuted(batch_request_p->hash(), batch_request_p->seq());
+ if (duplicate_manager_ && batch_request_p) {
+ duplicate_manager_->AddExecuted(batch_request_p->hash(),
+ batch_request_p->seq());
}
if (response == nullptr) {
@@ -334,11 +356,11 @@ void TransactionExecutor::Execute(std::unique_ptr<Request> request,
}
global_stats_->IncTotalRequest(batch_request_p->user_requests_size());
response->set_proxy_id(batch_request_p->proxy_id());
- response->set_createtime(batch_request_p->createtime() + request->queuing_time());
+ response->set_createtime(batch_request_p->createtime() +
+ request->queuing_time());
response->set_local_id(batch_request_p->local_id());
response->set_seq(request->seq());
-
if (post_exec_func_) {
post_exec_func_(std::move(request), std::move(response));
}
@@ -350,7 +372,6 @@ void TransactionExecutor::SetDuplicateManager(DuplicateManager* manager) {
duplicate_manager_ = manager;
}
-
bool TransactionExecutor::SetFlag(uint64_t uid, int f) {
std::unique_lock<std::mutex> lk(f_mutex_[uid % mod]);
auto it = flag_[uid % mod].find(uid);
@@ -364,9 +385,9 @@ bool TransactionExecutor::SetFlag(uint64_t uid, int f) {
if (flag_[uid % mod][uid] & Start_Execute) {
return false;
}
- } else if(f == Start_Execute){
+ } else if (f == Start_Execute) {
if (flag_[uid % mod][uid] & End_Prepare) {
- //if (flag_[uid % mod][uid] & Start_Prepare) {
+ // if (flag_[uid % mod][uid] & Start_Prepare) {
return false;
}
}
@@ -383,10 +404,10 @@ void TransactionExecutor::ClearPromise(uint64_t uid) {
// LOG(ERROR)<<"CLEAR UID:"<<uid;
assert(it != pre_[uid % mod].end());
assert(flag_[uid % mod].find(uid) != flag_[uid % mod].end());
- //assert(data_[uid%mod].find(uid) != data_[uid%mod].end());
- //assert(req_[uid%mod].find(uid) != req_[uid%mod].end());
- //data_[uid%mod].erase(data_[uid%mod].find(uid));
- //req_[uid%mod].erase(req_[uid%mod].find(uid));
+ // assert(data_[uid%mod].find(uid) != data_[uid%mod].end());
+ // assert(req_[uid%mod].find(uid) != req_[uid%mod].end());
+ // data_[uid%mod].erase(data_[uid%mod].find(uid));
+ // req_[uid%mod].erase(req_[uid%mod].find(uid));
pre_[uid % mod].erase(it);
flag_[uid % mod].erase(flag_[uid % mod].find(uid));
}
@@ -406,7 +427,7 @@ std::unique_ptr<std::future<int>> TransactionExecutor::GetFuture(uint64_t uid) {
if (it == pre_[uid % mod].end()) {
return nullptr;
}
- //return std::move(it->second);
+ // return std::move(it->second);
// LOG(ERROR)<<"add future:"<<uid;
return std::make_unique<std::future<int>>(it->second->get_future());
}
@@ -418,9 +439,9 @@ bool TransactionExecutor::AddFuture(uint64_t uid) {
// LOG(ERROR)<<"add future:"<<uid;
std::unique_ptr<std::promise<int>> p =
std::make_unique<std::promise<int>>();
- //auto f = std::make_unique<std::future<int>>(p->get_future());
+ // auto f = std::make_unique<std::future<int>>(p->get_future());
pre_[uid % mod][uid] = std::move(p);
- //pre_f_[uid % mod][uid] = std::move(f);
+ // pre_f_[uid % mod][uid] = std::move(f);
flag_[uid % mod][uid] = 0;
return true;
}
@@ -445,13 +466,13 @@ void TransactionExecutor::PrepareMessage() {
if (current_f == 0) {
// commit has done
// LOG(ERROR)<<" want prepare, commit started:"<<uid;
-// ClearPromise(uid);
+ // ClearPromise(uid);
continue;
}
- std::promise<int>* p = GetPromise(uid) ;
+ std::promise<int>* p = GetPromise(uid);
assert(p);
- //LOG(ERROR)<<" prepare started:"<<uid;
+ // LOG(ERROR)<<" prepare started:"<<uid;
// LOG(ERROR)<<" prepare uid:"<<uid;
@@ -473,27 +494,26 @@ void TransactionExecutor::PrepareMessage() {
// id:"<<request->proxy_id()<<" local id:"<<batch_request->local_id();
std::unique_ptr<std::vector<std::unique_ptr<google::protobuf::Message>>>
- request_v = transaction_manager_->Prepare(*batch_request);
+ request_v = transaction_manager_->Prepare(*batch_request);
{
std::unique_lock<std::mutex> lk(fd_mutex_[uid % mod]);
- // assert(request_v);
+ // assert(request_v);
// assert(data_[uid%mod].find(uid) == data_[uid%mod].end());
- data_[uid%mod][uid] = std::move(request_v);
+ data_[uid % mod][uid] = std::move(request_v);
req_[uid % mod][uid] = std::move(batch_request);
}
- //LOG(ERROR)<<"set promise:"<<uid;
+ // LOG(ERROR)<<"set promise:"<<uid;
p->set_value(1);
{
int set_ret = SetFlag(uid, End_Prepare);
if (set_ret == 0) {
// LOG(ERROR)<<"commit interrupt:"<<uid;
- //ClearPromise(uid);
+ // ClearPromise(uid);
} else {
- //LOG(ERROR)<<"prepare done:"<<uid;
+ // LOG(ERROR)<<"prepare done:"<<uid;
}
}
}
}
-
} // namespace resdb
diff --git a/platform/consensus/execution/transaction_executor.h b/platform/consensus/execution/transaction_executor.h
index 6fb8ef39..4d330279 100644
--- a/platform/consensus/execution/transaction_executor.h
+++ b/platform/consensus/execution/transaction_executor.h
@@ -53,6 +53,7 @@ class TransactionExecutor {
// The max seq S that can be executed (have received all the seq before S).
uint64_t GetMaxPendingExecutedSeq();
+ void SetPendingExecutedSeq(int seq);
// When a transaction is ready to be executed (have received all the seq
// before Txn) PreExecute func will be called.
@@ -75,7 +76,6 @@ class TransactionExecutor {
private:
void Execute(std::unique_ptr<Request> request, bool need_execute = true);
void OnlyExecute(std::unique_ptr<Request> request);
-
std::unique_ptr<std::string> DoExecute(const Request& request);
void OrderMessage();
void ExecuteMessage();
@@ -117,7 +117,8 @@ class TransactionExecutor {
static const int blucket_num_ = 1024;
int blucket_[blucket_num_];
std::condition_variable cv_;
- std::mutex mutex_;
+ std::mutex mutex_, e_mutex_;
+ int32_t last_seq_ = 0;
enum PrepareType {
Start_Prepare = 1,
@@ -125,7 +126,6 @@ class TransactionExecutor {
End_Prepare = 4,
};
-
std::vector<std::thread> prepare_thread_;
static const int mod = 2048;
std::mutex f_mutex_[mod], fd_mutex_[mod];
@@ -142,7 +142,6 @@ class TransactionExecutor {
uint64_t,
std::unique_ptr<std::vector<std::unique_ptr<google::protobuf::Message>>>>
data_[mod];
-
};
} // namespace resdb
diff --git a/platform/consensus/ordering/pbft/BUILD b/platform/consensus/ordering/pbft/BUILD
index 6f4fdff7..9afd1238 100644
--- a/platform/consensus/ordering/pbft/BUILD
+++ b/platform/consensus/ordering/pbft/BUILD
@@ -193,9 +193,9 @@ cc_library(
srcs = ["query.cpp"],
hdrs = ["query.h"],
deps = [
- ":message_manager",
"//executor/common:custom_query",
"//platform/config:resdb_config",
+ "//platform/consensus/recovery",
"//platform/proto:resdb_cc_proto",
],
)
diff --git a/platform/consensus/ordering/pbft/checkpoint_manager.cpp b/platform/consensus/ordering/pbft/checkpoint_manager.cpp
index a5a24ca8..323c12d5 100644
--- a/platform/consensus/ordering/pbft/checkpoint_manager.cpp
+++ b/platform/consensus/ordering/pbft/checkpoint_manager.cpp
@@ -31,7 +31,6 @@ CheckPointManager::CheckPointManager(const ResDBConfig& config,
SignatureVerifier* verifier)
: config_(config),
replica_communicator_(replica_communicator),
- txn_db_(std::make_unique<ChainState>()),
verifier_(verifier),
stop_(false),
txn_accessor_(config),
@@ -45,6 +44,7 @@ CheckPointManager::CheckPointManager(const ResDBConfig& config,
std::thread(&CheckPointManager::UpdateStableCheckPointStatus, this);
checkpoint_thread_ =
std::thread(&CheckPointManager::UpdateCheckPointStatus, this);
+ status_thread_ = std::thread(&CheckPointManager::SyncStatus, this);
}
sem_init(&committable_seq_signal_, 0, 0);
}
@@ -59,16 +59,15 @@ void CheckPointManager::Stop() {
if (stable_checkpoint_thread_.joinable()) {
stable_checkpoint_thread_.join();
}
+ if (status_thread_.joinable()) {
+ status_thread_.join();
+ }
}
std::string GetHash(const std::string& h1, const std::string& h2) {
return SignatureVerifier::CalculateHash(h1 + h2);
}
-ChainState* CheckPointManager::GetTxnDB() { return txn_db_.get(); }
-
-uint64_t CheckPointManager::GetMaxTxnSeq() { return txn_db_->GetMaxSeq(); }
-
uint64_t CheckPointManager::GetStableCheckpoint() {
std::lock_guard<std::mutex> lk(mutex_);
return current_stable_seq_;
@@ -82,8 +81,6 @@ StableCheckPoint CheckPointManager::GetStableCheckpointWithVotes() {
void CheckPointManager::AddCommitData(std::unique_ptr<Request> request) {
if (config_.IsCheckPointEnabled()) {
data_queue_.Push(std::move(request));
- } else {
- txn_db_->Put(std::move(request));
}
}
@@ -181,57 +178,6 @@ void CheckPointManager::UpdateStableCheckPointStatus() {
std::set<uint32_t> senders_ =
sender_ckpt_[std::make_pair(committable_seq_, committable_hash_)];
sem_post(&committable_seq_signal_);
- if (last_seq_ < committable_seq_ &&
- last_committable_seq < committable_seq_) {
- auto replicas_ = config_.GetReplicaInfos();
- for (auto& replica_ : replicas_) {
- std::string last_hash;
- uint64_t last_seq;
- {
- std::lock_guard<std::mutex> lk(lt_mutex_);
- last_hash = last_hash_;
- // last_seq_ = last_seq > last_committable_seq ? last_seq :
- // last_committable_seq;
- last_seq = last_seq_;
- }
- if (senders_.count(replica_.id()) &&
- last_seq < committable_seq_) {
- // LOG(ERROR) << "GetRequestFromReplica " << last_seq_ + 1 << "
- // " << committable_seq_;
- auto requests = txn_accessor_.GetRequestFromReplica(
- last_seq + 1, committable_seq_, replica_);
- if (requests.ok()) {
- bool fail = false;
- for (auto& request : *requests) {
- if (SignatureVerifier::CalculateHash(request.data()) !=
- request.hash()) {
- LOG(ERROR)
- << "The hash of the request does not match the data.";
- fail = true;
- break;
- }
- last_hash = GetHash(last_hash, request.hash());
- }
- if (fail) {
- continue;
- } else if (last_hash != committable_hash_) {
- LOG(ERROR) << "The hash of requests returned do not match. "
- << last_seq + 1 << " " << committable_seq_;
- } else {
- last_committable_seq = committable_seq_;
- for (auto& request : *requests) {
- if (executor_) {
- executor_->Commit(std::make_unique<Request>(request));
- }
- }
- SetHighestPreparedSeq(committable_seq_);
- // LOG(ERROR) << "[4]";
- break;
- }
- }
- }
- }
- }
}
if (it.second.size() >=
static_cast<size_t>(config_.GetMinDataReceiveNum())) {
@@ -287,24 +233,101 @@ void CheckPointManager::TimeoutHandler() {
}
}
+void CheckPointManager::SetLastCommit(uint64_t seq) { last_seq_ = seq; }
+
+int CheckPointManager::ProcessStatusSync(std::unique_ptr<Context> context,
+ std::unique_ptr<Request> request) {
+ CheckPointData checkpoint_data;
+ if (!checkpoint_data.ParseFromString(request->data())) {
+ LOG(ERROR) << "parse checkpont data fail:";
+ return -2;
+ }
+ uint64_t seq = checkpoint_data.seq();
+ uint32_t sender_id = request->sender_id();
+ status_[sender_id] = seq;
+ LOG(ERROR) << " received from :" << sender_id << " commit status:" << seq;
+ return 0;
+}
+
+void CheckPointManager::CheckStatus(uint64_t last_seq) {
+ std::vector<uint64_t> seqs;
+ for (auto it : status_) {
+ seqs.push_back(it.second);
+ }
+
+ sort(seqs.begin(), seqs.end());
+ int f = config_.GetMaxMaliciousReplicaNum();
+
+ if (seqs.size() <= f + 1) {
+ return;
+ }
+ uint64_t min_seq = seqs[f + 1];
+
+ LOG(ERROR) << " check last seq:" << last_seq << " max seq:" << min_seq;
+ if (last_seq < min_seq) {
+ // need recovery from others
+ BroadcastRecovery(last_seq + 1, std::min(min_seq, last_seq + 100));
+ }
+}
+
+void CheckPointManager::SyncStatus() {
+ uint64_t last_check_seq = 0;
+ uint64_t last_time = 0;
+ while (!stop_) {
+ uint64_t last_seq = last_seq_;
+
+ CheckPointData checkpoint_data;
+ std::unique_ptr<Request> checkpoint_request = NewRequest(
+ Request::TYPE_STATUS_SYNC, Request(), config_.GetSelfInfo().id());
+ checkpoint_data.set_seq(last_seq);
+ checkpoint_data.SerializeToString(checkpoint_request->mutable_data());
+ replica_communicator_->BroadCast(*checkpoint_request);
+
+ LOG(ERROR) << " sync status last seq:" << last_seq
+ << " last time:" << last_time;
+ if (last_check_seq == last_seq && last_time > 300) {
+ CheckStatus(last_seq);
+ last_time = 0;
+ }
+ if (last_seq != last_check_seq) {
+ last_check_seq = last_seq;
+ last_time = 0;
+ }
+ sleep(10);
+ last_time++;
+ }
+}
+
void CheckPointManager::UpdateCheckPointStatus() {
uint64_t last_ckpt_seq = 0;
int water_mark = config_.GetCheckPointWaterMark();
int timeout_ms = config_.GetViewchangeCommitTimeout();
std::vector<std::string> stable_hashs;
std::vector<uint64_t> stable_seqs;
+ std::map<uint64_t, std::unique_ptr<Request>> pendings;
while (!stop_) {
- auto request = data_queue_.Pop(timeout_ms);
+ std::unique_ptr<Request> request = nullptr;
+ if (!pendings.empty()) {
+ if (pendings.begin()->second->seq() == last_seq_ + 1) {
+ request = std::move(pendings.begin()->second);
+ pendings.erase(pendings.begin());
+ }
+ }
+ if (request == nullptr) {
+ request = data_queue_.Pop(timeout_ms);
+ }
if (request == nullptr) {
- // if (last_seq > 0) {
- // TimeoutHandler();
- // }
continue;
}
std::string hash_ = request->hash();
uint64_t current_seq = request->seq();
+ // LOG(ERROR) << "update checkpoint seq :" << last_seq_ << " current:" <<
+ // current_seq;
if (current_seq != last_seq_ + 1) {
LOG(ERROR) << "seq invalid:" << last_seq_ << " current:" << current_seq;
+ if (current_seq > last_seq_ + 1) {
+ pendings[current_seq] = std::move(request);
+ }
continue;
}
{
@@ -313,7 +336,6 @@ void CheckPointManager::UpdateCheckPointStatus() {
last_seq_++;
}
bool is_recovery = request->is_recovery();
- txn_db_->Put(std::move(request));
if (current_seq == last_ckpt_seq + water_mark) {
last_ckpt_seq = current_seq;
@@ -348,6 +370,18 @@ void CheckPointManager::BroadcastCheckPoint(
replica_communicator_->BroadCast(*checkpoint_request);
}
+void CheckPointManager::BroadcastRecovery(uint64_t min_seq, uint64_t max_seq) {
+ RecoveryRequest recovery_data;
+ std::unique_ptr<Request> recovery_request = NewRequest(
+ Request::TYPE_RECOVERY_DATA, Request(), config_.GetSelfInfo().id());
+ recovery_data.set_min_seq(min_seq);
+ recovery_data.set_max_seq(max_seq);
+ recovery_data.SerializeToString(recovery_request->mutable_data());
+
+ LOG(ERROR) << " recovery request [" << min_seq << "," << max_seq << "]";
+ replica_communicator_->BroadCast(*recovery_request);
+}
+
void CheckPointManager::WaitSignal() {
std::unique_lock<std::mutex> lk(mutex_);
signal_.wait(lk, [&] { return !stable_hash_queue_.Empty(); });
@@ -378,4 +412,8 @@ uint64_t CheckPointManager::GetCommittableSeq() {
return committable_seq_;
}
+// void CheckPointManager::SetLastExecutedSeq(uint64_t latest_executed_seq){
+// latest_executed_seq = executor_->get_latest_executed_seq();
+// }
+
} // namespace resdb
diff --git a/platform/consensus/ordering/pbft/checkpoint_manager.h b/platform/consensus/ordering/pbft/checkpoint_manager.h
index e043978e..8152311a 100644
--- a/platform/consensus/ordering/pbft/checkpoint_manager.h
+++ b/platform/consensus/ordering/pbft/checkpoint_manager.h
@@ -41,14 +41,16 @@ class CheckPointManager : public CheckPoint {
SignatureVerifier* verifier);
virtual ~CheckPointManager();
- ChainState* GetTxnDB();
- uint64_t GetMaxTxnSeq();
+ void SetLastCommit(uint64_t seq);
void AddCommitData(std::unique_ptr<Request> request);
int ProcessCheckPoint(std::unique_ptr<Context> context,
std::unique_ptr<Request> request);
+ int ProcessStatusSync(std::unique_ptr<Context> context,
+ std::unique_ptr<Request> request);
uint64_t GetStableCheckpoint() override;
+ // void SetLastExecutedSeq(uint64_t latest_executed_seq);
StableCheckPoint GetStableCheckpointWithVotes();
bool IsValidCheckpointProof(const StableCheckPoint& stable_ckpt);
@@ -82,12 +84,17 @@ class CheckPointManager : public CheckPoint {
void Notify();
bool Wait();
+ void BroadcastRecovery(uint64_t min_seq, uint64_t max_seq);
+
+ void SyncStatus();
+ void StatusProcess();
+ void CheckStatus(uint64_t last_seq);
protected:
+ uint64_t last_executed_seq_ = 0;
ResDBConfig config_;
ReplicaCommunicator* replica_communicator_;
- std::unique_ptr<ChainState> txn_db_;
- std::thread checkpoint_thread_, stable_checkpoint_thread_;
+ std::thread checkpoint_thread_, stable_checkpoint_thread_, status_thread_;
SignatureVerifier* verifier_;
std::atomic<bool> stop_;
std::map<std::pair<uint64_t, std::string>, std::set<uint32_t>> sender_ckpt_;
@@ -106,13 +113,15 @@ class CheckPointManager : public CheckPoint {
LockFreeQueue<std::pair<uint64_t, std::string>> stable_hash_queue_;
std::condition_variable signal_;
ResDBTxnAccessor txn_accessor_;
- std::mutex lt_mutex_;
+ std::mutex lt_mutex_, seq_mutex_;
uint64_t last_seq_ = 0;
+ uint64_t max_seq_ = 0;
TransactionExecutor* executor_;
std::atomic<uint64_t> highest_prepared_seq_;
uint64_t committable_seq_ = 0;
std::string last_hash_, committable_hash_;
sem_t committable_seq_signal_;
+ std::map<int, uint64_t> status_;
};
} // namespace resdb
diff --git a/platform/consensus/ordering/pbft/commitment.cpp b/platform/consensus/ordering/pbft/commitment.cpp
index 4d048331..914fc623 100644
--- a/platform/consensus/ordering/pbft/commitment.cpp
+++ b/platform/consensus/ordering/pbft/commitment.cpp
@@ -245,7 +245,7 @@ int Commitment::ProcessPrepareMsg(std::unique_ptr<Context> context,
return message_manager_->AddConsensusMsg(context->signature,
std::move(request));
}
- //global_stats_->IncPrepare();
+ // global_stats_->IncPrepare();
std::unique_ptr<Request> commit_request = resdb::NewRequest(
Request::TYPE_COMMIT, *request, config_.GetSelfInfo().id());
commit_request->mutable_data_signature()->Clear();
@@ -288,7 +288,7 @@ int Commitment::ProcessCommitMsg(std::unique_ptr<Context> context,
return message_manager_->AddConsensusMsg(context->signature,
std::move(request));
}
- //global_stats_->IncCommit();
+ // global_stats_->IncCommit();
// Add request to message_manager.
// If it has received enough same requests(2f+1), message manager will
// commit the request.
diff --git a/platform/consensus/ordering/pbft/consensus_manager_pbft.cpp b/platform/consensus/ordering/pbft/consensus_manager_pbft.cpp
index 72103eab..7425e3c7 100644
--- a/platform/consensus/ordering/pbft/consensus_manager_pbft.cpp
+++ b/platform/consensus/ordering/pbft/consensus_manager_pbft.cpp
@@ -39,8 +39,6 @@ ConsensusManagerPBFT::ConsensusManagerPBFT(
commitment_(std::make_unique<Commitment>(config_, message_manager_.get(),
GetBroadCastClient(),
GetSignatureVerifier())),
- query_(std::make_unique<Query>(config_, message_manager_.get(),
- std::move(query_executor))),
response_manager_(config_.IsPerformanceRunning()
? nullptr
: std::make_unique<ResponseManager>(
@@ -56,7 +54,9 @@ ConsensusManagerPBFT::ConsensusManagerPBFT(
system_info_.get(), GetBroadCastClient(), GetSignatureVerifier())),
recovery_(std::make_unique<Recovery>(config_, checkpoint_manager_.get(),
system_info_.get(),
- message_manager_->GetStorage())) {
+ message_manager_->GetStorage())),
+ query_(std::make_unique<Query>(config_, recovery_.get(),
+ std::move(query_executor))) {
LOG(INFO) << "is running is performance mode:"
<< config_.IsPerformanceRunning();
global_stats_ = Stats::GetGlobalStats();
@@ -70,14 +70,19 @@ ConsensusManagerPBFT::ConsensusManagerPBFT(
},
[&](std::unique_ptr<Context> context, std::unique_ptr<Request> request) {
return InternalConsensusCommit(std::move(context), std::move(request));
- });
+ },
+ [&](int seq) { message_manager_->SetNextCommitSeq(seq + 1); });
}
void ConsensusManagerPBFT::SetNeedCommitQC(bool need_qc) {
commitment_->SetNeedCommitQC(need_qc);
}
-void ConsensusManagerPBFT::Start() { ConsensusManager::Start(); }
+void ConsensusManagerPBFT::Start() {
+ ConsensusManager::Start();
+ recovery_thread_ =
+ std::thread(&ConsensusManagerPBFT::RemoteRecoveryProcess, this);
+}
std::vector<ReplicaInfo> ConsensusManagerPBFT::GetReplicas() {
return message_manager_->GetReplicas();
@@ -185,8 +190,8 @@ int ConsensusManagerPBFT::ConsensusCommit(std::unique_ptr<Context> context,
int ConsensusManagerPBFT::InternalConsensusCommit(
std::unique_ptr<Context> context, std::unique_ptr<Request> request) {
- // LOG(INFO) << "recv impl type:" << request->type() << " "
- // << "sender id:" << request->sender_id()<<" seq:"<<request->seq();
+ // LOG(ERROR) << "recv impl type:" << request->type() << " "
+ // << "sender id:" << request->sender_id()<<" seq:"<<request->seq();
switch (request->type()) {
case Request::TYPE_CLIENT_REQUEST:
@@ -236,6 +241,9 @@ int ConsensusManagerPBFT::InternalConsensusCommit(
case Request::TYPE_CHECKPOINT:
return checkpoint_manager_->ProcessCheckPoint(std::move(context),
std::move(request));
+ case Request::TYPE_STATUS_SYNC:
+ return checkpoint_manager_->ProcessStatusSync(std::move(context),
+ std::move(request));
case Request::TYPE_VIEWCHANGE:
return view_change_manager_->ProcessViewChange(std::move(context),
std::move(request));
@@ -249,6 +257,11 @@ int ConsensusManagerPBFT::InternalConsensusCommit(
std::move(request));
case Request::TYPE_CUSTOM_QUERY:
return query_->ProcessCustomQuery(std::move(context), std::move(request));
+ case Request::TYPE_RECOVERY_DATA:
+ return ProcessRecoveryData(std::move(context), std::move(request));
+ case Request::TYPE_RECOVERY_DATA_RESP:
+ return ProcessRecoveryDataResponse(std::move(context),
+ std::move(request));
}
return 0;
}
@@ -263,4 +276,83 @@ void ConsensusManagerPBFT::SetPreVerifyFunc(
commitment_->SetPreVerifyFunc(func);
}
+int ConsensusManagerPBFT::ProcessRecoveryData(
+ std::unique_ptr<Context> context, std::unique_ptr<Request> request) {
+ RecoveryRequest recovery_data;
+ if (!recovery_data.ParseFromString(request->data())) {
+ LOG(ERROR) << "parse checkpont data fail:";
+ return -2;
+ }
+ LOG(ERROR) << " obtain min seq:" << recovery_data.min_seq()
+ << " max seq:" << recovery_data.max_seq();
+ RecoveryResponse response;
+ int ret = recovery_->GetData(recovery_data, response);
+ if (ret) {
+ return ret;
+ }
+
+ std::unique_ptr<Request> response_data = NewRequest(
+ Request::TYPE_RECOVERY_DATA_RESP, Request(), config_.GetSelfInfo().id());
+
+ response.SerializeToString(response_data->mutable_data());
+
+ LOG(ERROR) << " obtain min seq:" << recovery_data.min_seq()
+ << " max seq:" << recovery_data.max_seq()
+ << " data size:" << response.request_size();
+
+ GetBroadCastClient()->SendMessage(*response_data, request->sender_id());
+
+ return 0;
+}
+
+int ConsensusManagerPBFT::ProcessRecoveryDataResponse(
+ std::unique_ptr<Context> context, std::unique_ptr<Request> request) {
+ recovery_queue_.Push(std::move(request));
+ return 0;
+}
+
+void ConsensusManagerPBFT::RemoteRecoveryProcess() {
+ uint64_t last_recovery = 0;
+ std::set<uint64_t> data;
+
+ while (IsRunning()) {
+ auto request = recovery_queue_.Pop();
+ if (request == nullptr) {
+ continue;
+ }
+
+ RecoveryResponse recovery_data;
+ if (!recovery_data.ParseFromString(request->data())) {
+ LOG(ERROR) << "parse checkpont data fail:";
+ continue;
+ }
+
+ LOG(ERROR) << " receive recovery data from " << request->sender_id()
+ << " data size:" << recovery_data.request_size()
+ << " signrue:" << recovery_data.signature_size();
+
+ for (int i = 0; i < recovery_data.request().size(); i++) {
+ uint64_t seq = recovery_data.request(i).seq();
+ int type = recovery_data.request(i).type();
+ if (data.find(seq) != data.end()) {
+ // LOG(ERROR)<<" check recovery remote seq:"<<seq<<" type:"<<type<<" has
+ // been recovered.";
+ continue;
+ }
+
+ auto context = std::make_unique<Context>();
+ context->signature = recovery_data.signature(i);
+ auto request = std::make_unique<Request>(recovery_data.request(i));
+ // write to log
+ // recovery_->AddRequest(context.get(), request.get());
+ InternalConsensusCommit(std::move(context), std::move(request));
+ }
+
+ for (int i = 0; i < recovery_data.request().size(); i++) {
+ uint64_t seq = recovery_data.request(i).seq();
+ data.insert(seq);
+ }
+ }
+}
+
} // namespace resdb
diff --git a/platform/consensus/ordering/pbft/consensus_manager_pbft.h b/platform/consensus/ordering/pbft/consensus_manager_pbft.h
index bea50990..4df5e9c2 100644
--- a/platform/consensus/ordering/pbft/consensus_manager_pbft.h
+++ b/platform/consensus/ordering/pbft/consensus_manager_pbft.h
@@ -55,6 +55,12 @@ class ConsensusManagerPBFT : public ConsensusManager {
void SetPreVerifyFunc(std::function<bool(const Request&)>);
void SetNeedCommitQC(bool need_qc);
+ int ProcessRecoveryData(std::unique_ptr<Context> context,
+ std::unique_ptr<Request> request);
+
+ int ProcessRecoveryDataResponse(std::unique_ptr<Context> context,
+ std::unique_ptr<Request> request);
+
protected:
int InternalConsensusCommit(std::unique_ptr<Context> context,
std::unique_ptr<Request> request);
@@ -67,6 +73,8 @@ class ConsensusManagerPBFT : public ConsensusManager {
absl::StatusOr<std::pair<std::unique_ptr<Context>, std::unique_ptr<Request>>>
PopComplainedRequest();
+ void RemoteRecoveryProcess();
+
protected:
std::unique_ptr<SystemInfo> system_info_;
std::unique_ptr<CheckPointManager> checkpoint_manager_;
@@ -83,6 +91,8 @@ class ConsensusManagerPBFT : public ConsensusManager {
std::queue<std::pair<std::unique_ptr<Context>, std::unique_ptr<Request>>>
request_complained_;
std::mutex mutex_;
+ std::thread recovery_thread_;
+ LockFreeQueue<Request> recovery_queue_;
};
} // namespace resdb
diff --git a/platform/consensus/ordering/pbft/lock_free_collector_pool.cpp b/platform/consensus/ordering/pbft/lock_free_collector_pool.cpp
index 4336b66d..bf335c17 100644
--- a/platform/consensus/ordering/pbft/lock_free_collector_pool.cpp
+++ b/platform/consensus/ordering/pbft/lock_free_collector_pool.cpp
@@ -50,6 +50,18 @@ LockFreeCollectorPool::LockFreeCollectorPool(const std::string& name,
<< " enable viewchange:" << enable_viewchange_ << " done";
}
+void LockFreeCollectorPool::Reset(uint64_t start_seq) {
+ uint32_t idx = start_seq & mask_;
+ int seq = start_seq;
+ LOG(ERROR) << " reset collector:" << start_seq;
+ for (size_t i = 0; i < (capacity_ << 1); ++i) {
+ int pos = (i + idx) % (capacity_ << 1);
+ collector_[pos] = std::make_unique<TransactionCollector>(
+ seq++, executor_, enable_viewchange_);
+ }
+ LOG(ERROR) << " reset collector:" << start_seq;
+}
+
void LockFreeCollectorPool::Update(uint64_t seq) {
uint32_t idx = seq & mask_;
if (collector_[idx]->Seq() != seq) {
diff --git a/platform/consensus/ordering/pbft/lock_free_collector_pool.h b/platform/consensus/ordering/pbft/lock_free_collector_pool.h
index 5335c4fd..22757827 100644
--- a/platform/consensus/ordering/pbft/lock_free_collector_pool.h
+++ b/platform/consensus/ordering/pbft/lock_free_collector_pool.h
@@ -33,6 +33,7 @@ class LockFreeCollectorPool {
TransactionCollector* GetCollector(uint64_t seq);
void Update(uint64_t seq);
+ void Reset(uint64_t start_seq);
private:
std::string name_;
diff --git a/platform/consensus/ordering/pbft/message_manager.cpp b/platform/consensus/ordering/pbft/message_manager.cpp
index cc5e187c..743f7aeb 100644
--- a/platform/consensus/ordering/pbft/message_manager.cpp
+++ b/platform/consensus/ordering/pbft/message_manager.cpp
@@ -31,7 +31,6 @@ MessageManager::MessageManager(
CheckPointManager* checkpoint_manager, SystemInfo* system_info)
: config_(config),
queue_("executed"),
- txn_db_(checkpoint_manager->GetTxnDB()),
system_info_(system_info),
checkpoint_manager_(checkpoint_manager),
transaction_executor_(std::make_unique<TransactionExecutor>(
@@ -177,6 +176,7 @@ CollectorResultCode MessageManager::AddConsensusMsg(
if (request == nullptr || !IsValidMsg(*request)) {
return CollectorResultCode::INVALID;
}
+
int type = request->type();
uint64_t seq = request->seq();
int resp_received_count = 0;
@@ -202,29 +202,6 @@ CollectorResultCode MessageManager::AddConsensusMsg(
return CollectorResultCode::OK;
}
-RequestSet MessageManager::GetRequestSet(uint64_t min_seq, uint64_t max_seq) {
- RequestSet ret;
- std::unique_lock<std::mutex> lk(data_mutex_);
- for (uint64_t i = min_seq; i <= max_seq; ++i) {
- if (committed_data_.find(i) == committed_data_.end()) {
- LOG(ERROR) << "seq :" << i << " doesn't exist";
- continue;
- }
- RequestWithProof* request = ret.add_requests();
- *request->mutable_request() = committed_data_[i];
- request->set_seq(i);
- for (const auto& request_info : committed_proof_[i]) {
- RequestWithProof::RequestData* data = request->add_proofs();
- *data->mutable_request() = *request_info->request;
- *data->mutable_signature() = request_info->signature;
- }
- }
- return ret;
-}
-
-// Get the transactions that have been execuited.
-Request* MessageManager::GetRequest(uint64_t seq) { return txn_db_->Get(seq); }
-
std::vector<RequestInfo> MessageManager::GetPreparedProof(uint64_t seq) {
return collector_pool_->GetCollector(seq)->GetPreparedProof();
}
@@ -242,6 +219,13 @@ Storage* MessageManager::GetStorage() {
return transaction_executor_->GetStorage();
}
+void MessageManager::SetNextCommitSeq(int seq) {
+ SetNextSeq(seq);
+ collector_pool_->Reset(seq);
+ checkpoint_manager_->SetLastCommit(seq);
+ return transaction_executor_->SetPendingExecutedSeq(seq);
+}
+
void MessageManager::SetLastCommittedTime(uint64_t proxy_id) {
lct_lock_.lock();
last_committed_time_[proxy_id] = GetCurrentTime();
diff --git a/platform/consensus/ordering/pbft/message_manager.h b/platform/consensus/ordering/pbft/message_manager.h
index c51fd22a..e31272fa 100644
--- a/platform/consensus/ordering/pbft/message_manager.h
+++ b/platform/consensus/ordering/pbft/message_manager.h
@@ -72,18 +72,14 @@ class MessageManager {
// to the client proxy.
std::unique_ptr<BatchUserResponse> GetResponseMsg();
- // Get committed messages with 2f+1 proof in [min_seq, max_seq].
- RequestSet GetRequestSet(uint64_t min_seq, uint64_t max_seq);
-
- // Get the transactions that have been execuited.
- Request* GetRequest(uint64_t seq);
-
// Get the proof info containing the request and signatures
// if the request has been prepared, having received 2f+1
// pre-prepare messages.
std::vector<RequestInfo> GetPreparedProof(uint64_t seq);
TransactionStatue GetTransactionState(uint64_t seq);
+ void SetNextCommitSeq(int seq);
+
// ============= System information ========
// Obtain the current replica list.
std::vector<ReplicaInfo> GetReplicas();
diff --git a/platform/consensus/ordering/pbft/query.cpp b/platform/consensus/ordering/pbft/query.cpp
index c2d60276..197caac4 100644
--- a/platform/consensus/ordering/pbft/query.cpp
+++ b/platform/consensus/ordering/pbft/query.cpp
@@ -24,10 +24,10 @@
namespace resdb {
-Query::Query(const ResDBConfig& config, MessageManager* message_manager,
+Query::Query(const ResDBConfig& config, Recovery* recovery,
std::unique_ptr<CustomQuery> executor)
: config_(config),
- message_manager_(message_manager),
+ recovery_(recovery),
custom_query_executor_(std::move(executor)) {}
Query::~Query() {}
@@ -35,17 +35,17 @@ Query::~Query() {}
int Query::ProcessGetReplicaState(std::unique_ptr<Context> context,
std::unique_ptr<Request> request) {
ReplicaState replica_state;
- int ret = message_manager_->GetReplicaState(&replica_state);
- if (ret == 0) {
- if (context != nullptr && context->client != nullptr) {
- ret = context->client->SendRawMessage(replica_state);
- if (ret) {
- LOG(ERROR) << "send resp" << replica_state.DebugString()
- << " fail ret:" << ret;
- }
+
+ *replica_state.mutable_replica_config() = config_.GetConfigData();
+
+ if (context != nullptr && context->client != nullptr) {
+ int ret = context->client->SendRawMessage(replica_state);
+ if (ret) {
+ LOG(ERROR) << "send resp" << replica_state.DebugString()
+ << " fail ret:" << ret;
}
}
- return ret;
+ return 0;
}
int Query::ProcessQuery(std::unique_ptr<Context> context,
@@ -64,6 +64,7 @@ int Query::ProcessQuery(std::unique_ptr<Context> context,
}
}
};
+
ReplicaInfo primary = find_primary();
std::string ip = primary.ip();
int port = primary.port();
@@ -94,20 +95,23 @@ int Query::ProcessQuery(std::unique_ptr<Context> context,
QueryResponse response;
if (query.max_seq() == 0 && query.min_seq() == 0) {
- uint64_t mseq = message_manager_->GetNextSeq();
- response.set_max_seq(mseq - 1);
+ uint64_t mseq = recovery_->GetMaxSeq();
+ response.set_max_seq(mseq);
LOG(ERROR) << "get max seq:" << mseq;
} else {
- for (uint64_t i = query.min_seq(); i <= query.max_seq(); ++i) {
- Request* ret_request = message_manager_->GetRequest(i);
- if (ret_request == nullptr) {
- break;
+ auto res =
+ recovery_->GetDataFromRecoveryFiles(query.min_seq(), query.max_seq());
+
+ for (const auto& it : res) {
+ for (const auto& req : it.second) {
+ Request* ret_request = req.second.get();
+
+ Request* txn = response.add_transactions();
+ txn->set_data(ret_request->data());
+ txn->set_hash(ret_request->hash());
+ txn->set_seq(ret_request->seq());
+ txn->set_proxy_id(ret_request->proxy_id());
}
- Request* txn = response.add_transactions();
- txn->set_data(ret_request->data());
- txn->set_hash(ret_request->hash());
- txn->set_seq(ret_request->seq());
- txn->set_proxy_id(ret_request->proxy_id());
}
}
diff --git a/platform/consensus/ordering/pbft/query.h b/platform/consensus/ordering/pbft/query.h
index e451cdfe..85f2e4c5 100644
--- a/platform/consensus/ordering/pbft/query.h
+++ b/platform/consensus/ordering/pbft/query.h
@@ -21,13 +21,13 @@
#include "executor/common/custom_query.h"
#include "platform/config/resdb_config.h"
-#include "platform/consensus/ordering/pbft/message_manager.h"
+#include "platform/consensus/recovery/recovery.h"
namespace resdb {
class Query {
public:
- Query(const ResDBConfig& config, MessageManager* message_manager,
+ Query(const ResDBConfig& config, Recovery* recovery,
std::unique_ptr<CustomQuery> executor = nullptr);
virtual ~Query();
@@ -41,7 +41,7 @@ class Query {
protected:
ResDBConfig config_;
- MessageManager* message_manager_;
+ Recovery* recovery_;
std::unique_ptr<CustomQuery> custom_query_executor_;
};
diff --git a/platform/consensus/ordering/pbft/query_test.cpp b/platform/consensus/ordering/pbft/query_test.cpp
index 871dfe52..25f276b1 100644
--- a/platform/consensus/ordering/pbft/query_test.cpp
+++ b/platform/consensus/ordering/pbft/query_test.cpp
@@ -61,7 +61,8 @@ class QueryTest : public Test {
system_info_(config_),
checkpoint_manager_(config_, &replica_communicator_, nullptr),
message_manager_(config_, nullptr, &checkpoint_manager_, &system_info_),
- query_(config_, &message_manager_),
+ recovery_(config_, &checkpoint_manager_, &system_info_, nullptr),
+ query_(config_, &recovery_),
commitment_(config_, &message_manager_, &replica_communicator_,
&verifier_) {}
@@ -136,6 +137,7 @@ class QueryTest : public Test {
SystemInfo system_info_;
CheckPointManager checkpoint_manager_;
MessageManager message_manager_;
+ Recovery recovery_;
Query query_;
MockReplicaCommunicator replica_communicator_;
MockSignatureVerifier verifier_;
diff --git a/platform/consensus/ordering/pbft/transaction_collector.cpp b/platform/consensus/ordering/pbft/transaction_collector.cpp
index 0c69c401..accb0536 100644
--- a/platform/consensus/ordering/pbft/transaction_collector.cpp
+++ b/platform/consensus/ordering/pbft/transaction_collector.cpp
@@ -90,8 +90,8 @@ int TransactionCollector::AddRequest(
}
if (seq_ != static_cast<uint64_t>(request->seq())) {
- // LOG(ERROR) << "data invalid, seq not the same:" << seq
- // << " collect seq:" << seq_;
+ LOG(ERROR) << "data invalid, seq not the same:" << seq
+ << " collect seq:" << seq_;
return -2;
}
diff --git a/platform/consensus/recovery/recovery.cpp b/platform/consensus/recovery/recovery.cpp
index 51faad5c..8c265b25 100644
--- a/platform/consensus/recovery/recovery.cpp
+++ b/platform/consensus/recovery/recovery.cpp
@@ -21,11 +21,14 @@
#include <fcntl.h>
#include <glog/logging.h>
+#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <filesystem>
+#include <fstream>
+#include <iostream>
#include "common/utils/utils.h"
@@ -52,6 +55,7 @@ Recovery::Recovery(const ResDBConfig& config, CheckPoint* checkpoint,
}
if (recovery_enabled_ == false) {
+ LOG(INFO) << "recovery is not enabled:" << recovery_enabled_;
return;
}
@@ -80,8 +84,10 @@ Recovery::Recovery(const ResDBConfig& config, CheckPoint* checkpoint,
}
void Recovery::Init() {
+ LOG(ERROR) << " init";
GetLastFile();
SwitchFile(file_path_);
+ LOG(ERROR) << " init done";
ckpt_thread_ = std::thread(&Recovery::UpdateStableCheckPoint, this);
}
@@ -138,6 +144,8 @@ void Recovery::GetLastFile() {
int64_t time_s =
std::stoll(file_name.substr(time_pos + 1, min_seq_pos - time_pos - 1));
+ LOG(ERROR) << "get path:" << entry.path() << " min:" << min_seq
+ << " time:" << time_s;
if (min_seq == -1) {
if (last_ckpt_ == -1 || m_time_s < time_s) {
file_path_ = entry.path();
@@ -382,7 +390,7 @@ bool Recovery::Read(int fd, size_t len, char* data) {
}
std::pair<std::vector<std::pair<int64_t, std::string>>, int64_t>
-Recovery::GetRecoveryFiles() {
+Recovery::GetRecoveryFiles(int64_t ckpt) {
std::string dir = std::filesystem::path(file_path_).parent_path();
int64_t last_ckpt = 0;
for (const auto& entry : std::filesystem::directory_iterator(dir)) {
@@ -396,6 +404,8 @@ Recovery::GetRecoveryFiles() {
last_ckpt = ckpt;
}
}
+ LOG(ERROR) << "file max ckpt:" << last_ckpt << " storage ckpt:" << ckpt;
+ last_ckpt = std::min(last_ckpt, ckpt);
std::vector<std::pair<int64_t, std::string>> list;
std::vector<std::pair<int64_t, std::string>> e_list;
@@ -437,13 +447,21 @@ void Recovery::ReadLogs(
std::function<void(const SystemInfoData& data)> system_callback,
std::function<void(std::unique_ptr<Context> context,
std::unique_ptr<Request> request)>
- call_back) {
+ call_back,
+ std::function<void(int)> set_start_point) {
if (recovery_enabled_ == false) {
return;
}
+ assert(storage_);
+ int64_t storage_ckpt = storage_->GetLastCheckpoint();
+ LOG(ERROR) << " storage ckpt:" << storage_ckpt;
std::unique_lock<std::mutex> lk(mutex_);
- auto recovery_files_pair = GetRecoveryFiles();
+
+ auto recovery_files_pair = GetRecoveryFiles(storage_ckpt);
int64_t ckpt = recovery_files_pair.second;
+ if (set_start_point) {
+ set_start_point(ckpt);
+ }
int idx = 0;
for (auto path : recovery_files_pair.first) {
ReadLogsFromFiles(path.second, ckpt, idx++, system_callback, call_back);
@@ -513,9 +531,14 @@ void Recovery::ReadLogsFromFiles(
}
uint64_t max_seq = 0;
for (std::unique_ptr<RecoveryData>& recovery_data : request_list) {
+ // LOG(ERROR)<<" ckpt :"<<ckpt<<" recovery data
+ // seq:"<<recovery_data->request->seq();
if (ckpt < recovery_data->request->seq()) {
recovery_data->request->set_is_recovery(true);
max_seq = recovery_data->request->seq();
+ // LOG(ERROR)<<" ??? call back:"<<recovery_data->request->seq()<<"
+ // call_back:"<<(call_back?"1":"0"); InsertCache(*recovery_data->context,
+ // *recovery_data->request);
call_back(std::move(recovery_data->context),
std::move(recovery_data->request));
}
@@ -527,4 +550,84 @@ void Recovery::ReadLogsFromFiles(
close(fd);
}
+int Recovery::GetData(const RecoveryRequest& request,
+ RecoveryResponse& response) {
+ auto res = GetDataFromRecoveryFiles(request.min_seq(), request.max_seq());
+
+ for (const auto& it : res) {
+ for (const auto& req : it.second) {
+ *response.add_signature() = req.first->signature;
+ *response.add_request() = *req.second;
+ }
+ }
+ return 0;
+}
+
+std::map<
+ uint64_t,
+ std::vector<std::pair<std::unique_ptr<Context>, std::unique_ptr<Request>>>>
+Recovery::GetDataFromRecoveryFiles(uint64_t need_min_seq,
+ uint64_t need_max_seq) {
+ std::string dir = std::filesystem::path(file_path_).parent_path();
+
+ std::vector<std::pair<int64_t, std::string>> list;
+ std::vector<std::pair<int64_t, std::string>> e_list;
+
+ for (const auto& entry : std::filesystem::directory_iterator(dir)) {
+ std::string dir = std::filesystem::path(entry.path()).parent_path();
+ std::string file_name = std::filesystem::path(entry.path()).stem();
+ std::string ext = std::filesystem::path(entry.path()).extension();
+ if (ext != ".log") continue;
+ int pos = file_name.rfind("_");
+
+ int max_seq_pos = file_name.rfind("_", pos - 1);
+ int64_t max_seq =
+ std::stoll(file_name.substr(max_seq_pos + 1, pos - max_seq_pos - 1));
+
+ int min_seq_pos = file_name.rfind("_", max_seq_pos - 1);
+ int64_t min_seq = std::stoll(
+ file_name.substr(min_seq_pos + 1, max_seq_pos - min_seq_pos - 1));
+
+ int time_pos = file_name.rfind("_", min_seq_pos - 1);
+ int64_t time =
+ std::stoll(file_name.substr(time_pos + 1, min_seq_pos - time_pos - 1));
+
+ // LOG(ERROR)<<" min seq:"<<min_seq << " max seq:"<<max_seq<<"
+ // need:"<<need_min_seq<<" "<<need_max_seq;
+ if (min_seq == -1) {
+ e_list.push_back(std::make_pair(time, entry.path()));
+ } else if (max_seq < need_min_seq || min_seq > need_max_seq) {
+ continue;
+ }
+ // LOG(ERROR)<<" get min seq:"<<min_seq << " max seq:"<<max_seq<<"
+ // need:"<<need_min_seq<<" "<<need_max_seq;
+ list.push_back(std::make_pair(time, entry.path()));
+ }
+
+ sort(e_list.begin(), e_list.end());
+ list.push_back(e_list.back());
+ sort(list.begin(), list.end());
+
+ std::map<uint64_t, std::vector<std::pair<std::unique_ptr<Context>,
+ std::unique_ptr<Request>>>>
+ res;
+ for (const auto& path : list) {
+ ReadLogsFromFiles(
+ path.second, need_min_seq - 1, 0, [&](const SystemInfoData& data) {},
+ [&](std::unique_ptr<Context> context,
+ std::unique_ptr<Request> request) {
+ LOG(ERROR) << "check get data from recovery file seq:"
+ << request->seq();
+ if (request->seq() >= need_min_seq &&
+ request->seq() <= need_max_seq) {
+ LOG(ERROR) << "get data from recovery file seq:" << request->seq();
+ res[request->seq()].push_back(
+ std::make_pair(std::move(context), std::move(request)));
+ }
+ });
+ }
+
+ return res;
+}
+
} // namespace resdb
diff --git a/platform/consensus/recovery/recovery.h b/platform/consensus/recovery/recovery.h
index 90f8fc99..426bffd2 100644
--- a/platform/consensus/recovery/recovery.h
+++ b/platform/consensus/recovery/recovery.h
@@ -40,15 +40,21 @@ class Recovery {
void Init();
virtual void AddRequest(const Context* context, const Request* request);
-
void ReadLogs(std::function<void(const SystemInfoData& data)> system_callback,
std::function<void(std::unique_ptr<Context> context,
std::unique_ptr<Request> request)>
- call_back);
+ call_back,
+ std::function<void(int)> start_point);
int64_t GetMaxSeq();
int64_t GetMinSeq();
+ int GetData(const RecoveryRequest& request, RecoveryResponse& response);
+
+ std::map<uint64_t, std::vector<std::pair<std::unique_ptr<Context>,
+ std::unique_ptr<Request>>>>
+ GetDataFromRecoveryFiles(uint64_t need_min_seq, uint64_t need_max_seq);
+
private:
struct RecoveryData {
std::unique_ptr<Context> context;
@@ -75,7 +81,7 @@ class Recovery {
void UpdateStableCheckPoint();
std::pair<std::vector<std::pair<int64_t, std::string>>, int64_t>
- GetRecoveryFiles();
+ GetRecoveryFiles(int64_t ckpt);
void ReadLogsFromFiles(
const std::string& path, int64_t ckpt, int file_idx,
std::function<void(const SystemInfoData& data)> system_callback,
@@ -83,6 +89,8 @@ class Recovery {
std::unique_ptr<Request> request)>
call_back);
+ void InsertCache(const Context& context, const Request& request);
+
protected:
ResDBConfig config_;
CheckPoint* checkpoint_;
@@ -92,7 +100,7 @@ class Recovery {
std::string file_path_, base_file_path_;
size_t buffer_size_ = 0;
int fd_;
- std::mutex mutex_;
+ std::mutex mutex_, data_mutex_;
int64_t last_ckpt_;
int64_t min_seq_, max_seq_;
diff --git a/platform/consensus/recovery/recovery_test.cpp b/platform/consensus/recovery/recovery_test.cpp
index a7cb1ef8..6c0dd25b 100644
--- a/platform/consensus/recovery/recovery_test.cpp
+++ b/platform/consensus/recovery/recovery_test.cpp
@@ -102,7 +102,8 @@ TEST_F(RecoveryTest, ReadLog) {
recovery.ReadLogs(
[&](const SystemInfoData &data) {},
[&](std::unique_ptr<Context> context,
- std::unique_ptr<Request> request) { list.push_back(*request); });
+ std::unique_ptr<Request> request) { list.push_back(*request); },
+ nullptr);
EXPECT_EQ(list.size(), expected_types.size());
@@ -143,7 +144,8 @@ TEST_F(RecoveryTest, ReadLog_FlushOnce) {
std::unique_ptr<Request> request) {
LOG(ERROR) << "call back:" << request->seq();
list.push_back(*request);
- });
+ },
+ nullptr);
EXPECT_EQ(list.size(), expected_types.size());
@@ -209,7 +211,8 @@ TEST_F(RecoveryTest, CheckPoint) {
std::unique_ptr<Request> request) {
list.push_back(*request);
// LOG(ERROR)<<"call back:"<<request->seq();
- });
+ },
+ nullptr);
EXPECT_EQ(list.size(), types.size() * 14);
@@ -286,7 +289,8 @@ TEST_F(RecoveryTest, CheckPoint2) {
std::unique_ptr<Request> request) {
list.push_back(*request);
// LOG(ERROR)<<"call back:"<<request->seq();
- });
+ },
+ nullptr);
EXPECT_EQ(list.size(), types.size() * 14);
@@ -323,7 +327,8 @@ TEST_F(RecoveryTest, CheckPoint2) {
std::unique_ptr<Request> request) {
list.push_back(*request);
// LOG(ERROR)<<"call back:"<<request->seq();
- });
+ },
+ nullptr);
EXPECT_EQ(list.size(), types.size() * 9);
@@ -405,7 +410,8 @@ TEST_F(RecoveryTest, SystemInfo) {
std::unique_ptr<Request> request) {
list.push_back(*request);
// LOG(ERROR)<<"call back:"<<request->seq();
- });
+ },
+ nullptr);
EXPECT_EQ(list.size(), types.size() * 14);
@@ -443,7 +449,8 @@ TEST_F(RecoveryTest, SystemInfo) {
std::unique_ptr<Request> request) {
list.push_back(*request);
// LOG(ERROR)<<"call back:"<<request->seq();
- });
+ },
+ nullptr);
EXPECT_EQ(data.view(), 2);
EXPECT_EQ(data.primary_id(), 2);
diff --git a/platform/networkstrate/replica_communicator.cpp b/platform/networkstrate/replica_communicator.cpp
index f1521acb..4205796a 100644
--- a/platform/networkstrate/replica_communicator.cpp
+++ b/platform/networkstrate/replica_communicator.cpp
@@ -43,10 +43,9 @@ ReplicaCommunicator::ReplicaCommunicator(
worker_threads_.push_back(std::thread([&]() { io_service_.run(); }));
}
}
- LOG(ERROR)<<" tcp batch:"<<tcp_batch;
+ LOG(ERROR) << " tcp batch:" << tcp_batch;
StartBroadcastInBackGround();
-
}
ReplicaCommunicator::~ReplicaCommunicator() {
@@ -124,8 +123,11 @@ void ReplicaCommunicator::StartBroadcastInBackGround() {
});
}
-void ReplicaCommunicator::StartSingleInBackGround(const std::string& ip, int port) {
- single_bq_[std::make_pair(ip,port)] = std::make_unique<BatchQueue<std::unique_ptr<QueueItem>>>("s_batch", tcp_batch_);
+void ReplicaCommunicator::StartSingleInBackGround(const std::string& ip,
+ int port) {
+ single_bq_[std::make_pair(ip, port)] =
+ std::make_unique<BatchQueue<std::unique_ptr<QueueItem>>>("s_batch",
+ tcp_batch_);
ReplicaInfo replica_info;
for (const auto& replica : replicas_) {
@@ -144,44 +146,46 @@ void ReplicaCommunicator::StartSingleInBackGround(const std::string& ip, int por
}
}
-
- single_thread_.push_back(std::thread([&](BatchQueue<std::unique_ptr<QueueItem>> *bq, ReplicaInfo replica_info) {
- while (IsRunning()) {
- std::vector<std::unique_ptr<QueueItem>> batch_req =
- bq->Pop(50000);
- if (batch_req.empty()) {
- continue;
- }
- BroadcastData broadcast_data;
- for (auto& queue_item : batch_req) {
- broadcast_data.add_data()->swap(queue_item->data);
- }
-
- global_stats_->SendBroadCastMsg(broadcast_data.data_size());
- //LOG(ERROR)<<" send to ip:"<<replica_info.ip()<<" port:"<<replica_info.port()<<" bq size:"<<batch_req.size();
- int ret = SendMessageFromPool(broadcast_data, {replica_info});
- if (ret < 0) {
- LOG(ERROR) << "broadcast request fail:";
- }
- //LOG(ERROR)<<" send to ip:"<<replica_info.ip()<<" port:"<<replica_info.port()<<" bq size:"<<batch_req.size()<<" done";
- }
- }, single_bq_[std::make_pair(ip,port)].get(), replica_info));
+ single_thread_.push_back(std::thread(
+ [&](BatchQueue<std::unique_ptr<QueueItem>>* bq,
+ ReplicaInfo replica_info) {
+ while (IsRunning()) {
+ std::vector<std::unique_ptr<QueueItem>> batch_req = bq->Pop(50000);
+ if (batch_req.empty()) {
+ continue;
+ }
+ BroadcastData broadcast_data;
+ for (auto& queue_item : batch_req) {
+ broadcast_data.add_data()->swap(queue_item->data);
+ }
+
+ global_stats_->SendBroadCastMsg(broadcast_data.data_size());
+ // LOG(ERROR)<<" send to ip:"<<replica_info.ip()<<"
+ // port:"<<replica_info.port()<<" bq size:"<<batch_req.size();
+ int ret = SendMessageFromPool(broadcast_data, {replica_info});
+ if (ret < 0) {
+ LOG(ERROR) << "broadcast request fail:";
+ }
+ // LOG(ERROR)<<" send to ip:"<<replica_info.ip()<<"
+ // port:"<<replica_info.port()<<" bq size:"<<batch_req.size()<<"
+ // done";
+ }
+ },
+ single_bq_[std::make_pair(ip, port)].get(), replica_info));
}
-
-int ReplicaCommunicator::SendSingleMessage(const google::protobuf::Message& message,
-const ReplicaInfo& replica_info) {
-
+int ReplicaCommunicator::SendSingleMessage(
+ const google::protobuf::Message& message, const ReplicaInfo& replica_info) {
std::string ip = replica_info.ip();
int port = replica_info.port();
- //LOG(ERROR)<<" send msg ip:"<<ip<<" port:"<<port;
+ // LOG(ERROR)<<" send msg ip:"<<ip<<" port:"<<port;
global_stats_->BroadCastMsg();
if (is_use_long_conn_) {
auto item = std::make_unique<QueueItem>();
item->data = NetChannel::GetRawMessageString(message, verifier_);
std::lock_guard<std::mutex> lk(smutex_);
- if(single_bq_.find(std::make_pair(ip, port)) == single_bq_.end()){
+ if (single_bq_.find(std::make_pair(ip, port)) == single_bq_.end()) {
StartSingleInBackGround(ip, port);
}
assert(single_bq_[std::make_pair(ip, port)] != nullptr);
@@ -250,13 +254,13 @@ int ReplicaCommunicator::SendMessageFromPool(
if (client == nullptr) {
continue;
}
- //LOG(ERROR) << "send to:" << replica.ip();
+ // LOG(ERROR) << "send to:" << replica.ip();
if (client->SendMessage(data) == 0) {
ret++;
} else {
LOG(ERROR) << "send to:" << replica.ip() << " fail";
}
- //LOG(ERROR) << "send to:" << replica.ip()<<" done";
+ // LOG(ERROR) << "send to:" << replica.ip()<<" done";
}
return ret;
}
@@ -286,7 +290,7 @@ AsyncReplicaClient* ReplicaCommunicator::GetClientFromPool(
auto client = std::make_unique<AsyncReplicaClient>(
&io_service_, ip, port + (is_use_long_conn_ ? 10000 : 0), true);
client_pools_[std::make_pair(ip, port)] = std::move(client);
- //StartSingleInBackGround(ip, port);
+ // StartSingleInBackGround(ip, port);
}
return client_pools_[std::make_pair(ip, port)].get();
}
diff --git a/platform/networkstrate/replica_communicator.h b/platform/networkstrate/replica_communicator.h
index 239e4d21..a9570369 100644
--- a/platform/networkstrate/replica_communicator.h
+++ b/platform/networkstrate/replica_communicator.h
@@ -75,8 +75,8 @@ class ReplicaCommunicator {
void StartSingleInBackGround(const std::string& ip, int port);
- int SendSingleMessage(const google::protobuf::Message& message,
- const ReplicaInfo& replica_info);
+ int SendSingleMessage(const google::protobuf::Message& message,
+ const ReplicaInfo& replica_info);
private:
std::vector<ReplicaInfo> replicas_;
@@ -98,11 +98,10 @@ class ReplicaCommunicator {
std::vector<std::thread> worker_threads_;
std::vector<ReplicaInfo> clients_;
std::mutex mutex_;
-
-
- std::map<std::pair<std::string, int>,
- std::unique_ptr<BatchQueue<std::unique_ptr<QueueItem>>>> single_bq_;
+ std::map<std::pair<std::string, int>,
+ std::unique_ptr<BatchQueue<std::unique_ptr<QueueItem>>>>
+ single_bq_;
std::vector<std::thread> single_thread_;
int tcp_batch_;
std::mutex smutex_;
diff --git a/platform/proto/resdb.proto b/platform/proto/resdb.proto
index 47edac38..5c2ccb60 100644
--- a/platform/proto/resdb.proto
+++ b/platform/proto/resdb.proto
@@ -57,8 +57,9 @@ message Request {
TYPE_NEWVIEW= 17;
TYPE_CUSTOM_QUERY = 18;
TYPE_CUSTOM_CONSENSUS = 19;
+ TYPE_STATUS_SYNC = 20;
- NUM_OF_TYPE = 20; // the total number of types.
+ NUM_OF_TYPE = 21; // the total number of types.
// Used to create the collector.
};
int32 type = 1;
@@ -175,6 +176,7 @@ message RecoveryRequest {
message RecoveryResponse {
repeated Request request = 1;
+ repeated SignatureInfo signature = 2;
}
message RequestWithProof {
diff --git a/platform/statistic/BUILD b/platform/statistic/BUILD
index 3094840b..92328f16 100644
--- a/platform/statistic/BUILD
+++ b/platform/statistic/BUILD
@@ -17,9 +17,9 @@
#
package(default_visibility = [
+ "//chain/storage:__subpackages__",
"//platform:__subpackages__",
"//service:__subpackages__",
- "//chain/storage:__subpackages__",
])
cc_library(
diff --git a/platform/statistic/set_random_data.cpp b/platform/statistic/set_random_data.cpp
index fba5e327..d2af8007 100644
--- a/platform/statistic/set_random_data.cpp
+++ b/platform/statistic/set_random_data.cpp
@@ -67,8 +67,8 @@ int main(int argc, char** argv) {
std::stringstream ss;
ss << " bazel-bin/service/tools/kv/api_tools/kv_service_tools --config "
"service/tools/config/interface/service.config --cmd set "
- << "--key key" << (std::rand() % 500) << " " << "--value value"
- << (std::rand() % 500);
+ << "--key key" << (std::rand() % 500) << " "
+ << "--value value" << (std::rand() % 500);
std::string test = ss.str();
output = Exec(test.c_str());
diff --git a/scripts/deploy/config/kv_server.conf b/scripts/deploy/config/kv_server.conf
index abfc222e..d5af12e6 100644
--- a/scripts/deploy/config/kv_server.conf
+++ b/scripts/deploy/config/kv_server.conf
@@ -18,10 +18,10 @@
#
iplist=(
-172.31.25.4
-172.31.27.205
-172.31.27.141
-172.31.20.222
-172.31.28.162
+172.31.57.186
+172.31.57.186
+172.31.57.186
+172.31.57.186
+172.31.57.186
)
diff --git a/scripts/deploy/script/deploy.sh b/scripts/deploy/script/deploy.sh
index 8bae565b..bab480bb 100755
--- a/scripts/deploy/script/deploy.sh
+++ b/scripts/deploy/script/deploy.sh
@@ -19,6 +19,8 @@
set -e
+export TEMPLATE_PATH=$PWD/config/pbft.config
+
# load environment parameters
. ./script/env.sh
@@ -70,7 +72,8 @@ deploy/script/generate_key.sh ${BAZEL_WORKSPACE_PATH} ${output_key_path} ${#ipli
deploy/script/generate_config.sh ${BAZEL_WORKSPACE_PATH} ${output_key_path} ${output_cert_path} ${output_path} ${admin_key_path} ${deploy_iplist[@]}
# build kv server
-bazel build ${server}
+#bazel build ${server}
+bazel build ${server} --define="enable_leveldb=True"
if [ $? != 0 ]
then
diff --git a/scripts/format.sh b/scripts/format.sh
index 2c255ba1..fe25b4c7 100644
--- a/scripts/format.sh
+++ b/scripts/format.sh
@@ -17,6 +17,7 @@
# under the License.
#
+cd ..
bazel build @com_github_bazelbuild_buildtools//buildifier:buildifier
find . ! -path "./deps/*" -type f -regex ".*\.cpp\|.*\.h" | xargs clang-format -i
bazel-bin/external/com_github_bazelbuild_buildtools/buildifier/buildifier_/buildifier -r .
diff --git a/service/contract/BUILD b/service/contract/BUILD
index d97c304b..d2f5bafe 100644
--- a/service/contract/BUILD
+++ b/service/contract/BUILD
@@ -22,10 +22,10 @@ cc_binary(
name = "contract_service",
srcs = ["contract_service.cpp"],
deps = [
+ "//chain/storage:memory_db",
"//executor/contract/executor:contract_executor",
"//platform/config:resdb_config_utils",
"//platform/consensus/ordering/pbft:consensus_manager_pbft",
"//service/utils:server_factory",
- "//chain/storage:memory_db",
],
)
diff --git a/service/contract/contract_service.cpp b/service/contract/contract_service.cpp
index 5bcc8942..b1f10721 100644
--- a/service/contract/contract_service.cpp
+++ b/service/contract/contract_service.cpp
@@ -66,7 +66,8 @@ int main(int argc, char** argv) {
std::unique_ptr<resdb::Storage> memory_db = resdb::storage::NewMemoryDB();
auto server = CustomGenerateResDBServer<ConsensusManagerPBFT>(
config_file, private_key_file, cert_file,
- std::make_unique<ContractTransactionManager>(memory_db.get()), logging_dir);
+ std::make_unique<ContractTransactionManager>(memory_db.get()),
+ logging_dir);
server->Run();
}
diff --git a/service/kv/BUILD b/service/kv/BUILD
index e6ac6dd4..0e44111f 100644
--- a/service/kv/BUILD
+++ b/service/kv/BUILD
@@ -27,7 +27,6 @@ cc_binary(
copts = select({
"//chain/storage/setting:enable_leveldb_setting": ["-DENABLE_LEVELDB"],
"//conditions:default": [],
-
}),
deps = [
"//platform/config:resdb_config_utils",
@@ -36,7 +35,7 @@ cc_binary(
"//common:comm",
"//proto/kv:kv_cc_proto",
"//chain/storage:memory_db",
- ] + select({
+ ] + select({
"//chain/storage/setting:enable_leveldb_setting": ["//chain/storage:leveldb"],
"//conditions:default": [],
}),
diff --git a/service/kv/kv_service.cpp b/service/kv/kv_service.cpp
index 269fb807..a3d2fabd 100644
--- a/service/kv/kv_service.cpp
+++ b/service/kv/kv_service.cpp
@@ -31,6 +31,11 @@
using namespace resdb;
using namespace resdb::storage;
+void SignalHandler(int sig_num) {
+ LOG(ERROR) << " signal:" << sig_num << " call"
+ << " ======================";
+}
+
void ShowUsage() {
printf("<config> <private_key> <cert_file> [logging_dir]\n");
}
@@ -51,7 +56,9 @@ int main(int argc, char** argv) {
exit(0);
}
google::InitGoogleLogging(argv[0]);
- FLAGS_minloglevel = 1;
+ FLAGS_minloglevel = 0;
+ signal(SIGINT, SignalHandler);
+ signal(SIGKILL, SignalHandler);
char* config_file = argv[1];
char* private_key_file = argv[2];
@@ -71,10 +78,10 @@ int main(int argc, char** argv) {
ResConfigData config_data = config->GetConfigData();
std::string db_path = std::to_string(config->GetSelfInfo().port()) + "_db/";
- LOG(INFO) << "db path:" << db_path;
+ LOG(ERROR) << "db path:" << db_path;
auto server = GenerateResDBServer(
config_file, private_key_file, cert_file,
std::make_unique<KVExecutor>(NewStorage(db_path, config_data)), nullptr);
server->Run();
-}
\ No newline at end of file
+}
diff --git a/service/tools/contract/api_tools/contract_tools.cpp b/service/tools/contract/api_tools/contract_tools.cpp
index 72e7a73e..0f1f0310 100644
--- a/service/tools/contract/api_tools/contract_tools.cpp
+++ b/service/tools/contract/api_tools/contract_tools.cpp
@@ -17,13 +17,13 @@
* under the License.
*/
+#include <getopt.h>
#include <glog/logging.h>
-#include <getopt.h>
-#include <nlohmann/json.hpp>
#include <boost/algorithm/string.hpp>
-#include <vector>
#include <fstream>
+#include <nlohmann/json.hpp>
+#include <vector>
#include "interface/contract/contract_client.h"
#include "platform/config/resdb_config_utils.h"
@@ -32,8 +32,6 @@ using resdb::GenerateResDBConfig;
using resdb::ResDBConfig;
using resdb::contract::ContractClient;
-
-
void ShowUsage() {
printf(
"<cmd> -c <config> -m <caller address> -n <contract name> -p <contact "
@@ -42,11 +40,9 @@ void ShowUsage() {
}
static struct option long_options[] = {
- { "cmd", required_argument, NULL, 'm'},
- { "config_file", required_argument, NULL, 'f'},
- { 0, 0, 0, 0 }
-};
-
+ {"cmd", required_argument, NULL, 'm'},
+ {"config_file", required_argument, NULL, 'f'},
+ {0, 0, 0, 0}};
void CreateAccount(ContractClient* client) {
auto account = client->CreateAccount();
@@ -84,40 +80,38 @@ void ExecuteContract(ContractClient* client, const std::string& caller_address,
}
nlohmann::json ReadJSConfig(const std::string& config_path) {
-
std::ifstream contract_fstream(config_path);
if (!contract_fstream) {
- throw std::runtime_error( "Unable to open config file "+config_path);
+ throw std::runtime_error("Unable to open config file " + config_path);
}
return nlohmann::json::parse(contract_fstream);
}
-std::string GetValue(const nlohmann::json& js, std::string key){
-if(!js.contains(key)){
- printf("need %s\n", key.c_str());
- exit(0);
- }
- return js[key];
+std::string GetValue(const nlohmann::json& js, std::string key) {
+ if (!js.contains(key)) {
+ printf("need %s\n", key.c_str());
+ exit(0);
+ }
+ return js[key];
}
-
int main(int argc, char** argv) {
if (argc < 2) {
printf("<cmd> -c [config]\n");
return 0;
}
-
std::string config_file;
-
+
std::string cmd;
std::string caller_address, contract_name, contract_path, params,
contract_address, func_name;
int c;
int option_index;
std::string client_config_file;
- while ((c = getopt_long(argc, argv, "c:h", long_options, &option_index)) != -1) {
+ while ((c = getopt_long(argc, argv, "c:h", long_options, &option_index)) !=
+ -1) {
switch (c) {
case -1:
break;
@@ -136,7 +130,8 @@ int main(int argc, char** argv) {
nlohmann::json js = ReadJSConfig(config_file);
cmd = GetValue(js, "command");
- printf("client config path = %s config path = %s cmd = %s\n", client_config_file.c_str(), config_file.c_str(), cmd.c_str());
+ printf("client config path = %s config path = %s cmd = %s\n",
+ client_config_file.c_str(), config_file.c_str(), cmd.c_str());
ResDBConfig config = GenerateResDBConfig(client_config_file);
config.SetClientTimeoutMs(100000);
@@ -145,13 +140,16 @@ int main(int argc, char** argv) {
if (cmd == "create_account") {
CreateAccount(&client);
} else if (cmd == "deploy") {
-
contract_path = GetValue(js, "contract_path");
contract_name = GetValue(js, "contract_name");
contract_address = GetValue(js, "contract_address");
params = GetValue(js, "init_params");
- printf("contract path %s cmd %s contract name %s caller_address %s init params %s\n", contract_path.c_str(), cmd.c_str(), contract_name.c_str(), contract_address.c_str(), params.c_str());
+ printf(
+ "contract path %s cmd %s contract name %s caller_address %s init "
+ "params %s\n",
+ contract_path.c_str(), cmd.c_str(), contract_name.c_str(),
+ contract_address.c_str(), params.c_str());
std::vector<std::string> init_params;
boost::split(init_params, params, boost::is_any_of(","));
@@ -159,7 +157,6 @@ int main(int argc, char** argv) {
DeployContract(&client, contract_address, contract_name, contract_path,
init_params);
} else if (cmd == "execute") {
-
caller_address = GetValue(js, "caller_address");
contract_address = GetValue(js, "contract_address");
func_name = GetValue(js, "func_name");
@@ -177,4 +174,3 @@ int main(int argc, char** argv) {
func_params);
}
}
-
diff --git a/service/tools/kv/api_tools/BUILD b/service/tools/kv/api_tools/BUILD
index a25b2f95..50d56289 100644
--- a/service/tools/kv/api_tools/BUILD
+++ b/service/tools/kv/api_tools/BUILD
@@ -33,14 +33,13 @@ cc_binary(
name = "contract_service_tools",
srcs = ["contract_service_tools.cpp"],
deps = [
+ "//common:boost_comm",
"//common/proto:signature_info_cc_proto",
"//interface/kv:contract_client",
"//platform/config:resdb_config_utils",
- "//common:boost_comm",
],
)
-
cc_binary(
name = "kv_client_txn_tools",
srcs = ["kv_client_txn_tools.cpp"],
diff --git a/service/tools/kv/api_tools/contract_service_tools.cpp b/service/tools/kv/api_tools/contract_service_tools.cpp
index d3aa2419..ffa64d36 100644
--- a/service/tools/kv/api_tools/contract_service_tools.cpp
+++ b/service/tools/kv/api_tools/contract_service_tools.cpp
@@ -17,13 +17,13 @@
* under the License.
*/
+#include <getopt.h>
#include <glog/logging.h>
-#include <getopt.h>
-#include <nlohmann/json.hpp>
#include <boost/algorithm/string.hpp>
-#include <vector>
#include <fstream>
+#include <nlohmann/json.hpp>
+#include <vector>
#include "interface/kv/contract_client.h"
#include "platform/config/resdb_config_utils.h"
@@ -33,20 +33,20 @@ using resdb::ResDBConfig;
using resdb::contract::ContractClient;
bool IsValidAddress(const std::string& address) {
- if (address.length() != 42) {
- return false;
- }
+ if (address.length() != 42) {
+ return false;
+ }
- if (address.substr(0, 2) != "0x") {
- return false;
- }
+ if (address.substr(0, 2) != "0x") {
+ return false;
+ }
- for (size_t i = 2; i < address.length(); ++i) {
- if (!std::isxdigit(address[i])) {
- return false;
- }
+ for (size_t i = 2; i < address.length(); ++i) {
+ if (!std::isxdigit(address[i])) {
+ return false;
}
- return true;
+ }
+ return true;
}
void ShowUsage() {
@@ -57,11 +57,9 @@ void ShowUsage() {
}
static struct option long_options[] = {
- { "cmd", required_argument, NULL, 'm'},
- { "config_file", required_argument, NULL, 'f'},
- { 0, 0, 0, 0 }
-};
-
+ {"cmd", required_argument, NULL, 'm'},
+ {"config_file", required_argument, NULL, 'f'},
+ {0, 0, 0, 0}};
void CreateAccount(ContractClient* client) {
auto account = client->CreateAccount();
@@ -99,40 +97,38 @@ void ExecuteContract(ContractClient* client, const std::string& caller_address,
}
nlohmann::json ReadJSConfig(const std::string& config_path) {
-
std::ifstream contract_fstream(config_path);
if (!contract_fstream) {
- throw std::runtime_error( "Unable to open config file "+config_path);
+ throw std::runtime_error("Unable to open config file " + config_path);
}
return nlohmann::json::parse(contract_fstream);
}
-std::string GetValue(const nlohmann::json& js, std::string key){
-if(!js.contains(key)){
- printf("need %s\n", key.c_str());
- exit(0);
- }
- return js[key];
+std::string GetValue(const nlohmann::json& js, std::string key) {
+ if (!js.contains(key)) {
+ printf("need %s\n", key.c_str());
+ exit(0);
+ }
+ return js[key];
}
-
int main(int argc, char** argv) {
if (argc < 2) {
printf("<cmd> -c [config]\n");
return 0;
}
-
std::string config_file;
-
+
std::string cmd;
std::string caller_address, contract_name, contract_path, params,
contract_address, func_name;
int c;
int option_index;
std::string client_config_file;
- while ((c = getopt_long(argc, argv, "c:h", long_options, &option_index)) != -1) {
+ while ((c = getopt_long(argc, argv, "c:h", long_options, &option_index)) !=
+ -1) {
switch (c) {
case -1:
break;
@@ -149,7 +145,7 @@ int main(int argc, char** argv) {
}
nlohmann::json js = ReadJSConfig(config_file);
- std::cout<<js<<std::endl;
+ std::cout << js << std::endl;
cmd = GetValue(js, "command");
ResDBConfig config = GenerateResDBConfig(client_config_file);
@@ -160,18 +156,22 @@ int main(int argc, char** argv) {
if (cmd == "create_account") {
CreateAccount(&client);
} else if (cmd == "deploy") {
-
contract_path = GetValue(js, "contract_path");
contract_name = GetValue(js, "contract_name");
contract_address = GetValue(js, "owner_address");
params = GetValue(js, "init_params");
if (!IsValidAddress(contract_address)) {
- printf("ERROR: Invalid owner address format: %s\n", contract_address.c_str());
- return 1;
+ printf("ERROR: Invalid owner address format: %s\n",
+ contract_address.c_str());
+ return 1;
}
- printf("contract path %s cmd %s contract name %s caller_address %s init params %s\n", contract_path.c_str(), cmd.c_str(), contract_name.c_str(), contract_address.c_str(), params.c_str());
+ printf(
+ "contract path %s cmd %s contract name %s caller_address %s init "
+ "params %s\n",
+ contract_path.c_str(), cmd.c_str(), contract_name.c_str(),
+ contract_address.c_str(), params.c_str());
std::vector<std::string> init_params;
boost::split(init_params, params, boost::is_any_of(","));
@@ -179,20 +179,21 @@ int main(int argc, char** argv) {
DeployContract(&client, contract_address, contract_name, contract_path,
init_params);
} else if (cmd == "execute") {
-
caller_address = GetValue(js, "caller_address");
contract_address = GetValue(js, "contract_address");
func_name = GetValue(js, "func_name");
params = GetValue(js, "params");
if (!IsValidAddress(caller_address)) {
- printf("ERROR: Invalid caller address format: %s\n", caller_address.c_str());
- return 1;
+ printf("ERROR: Invalid caller address format: %s\n",
+ caller_address.c_str());
+ return 1;
}
if (!IsValidAddress(contract_address)) {
- printf("ERROR: Invalid contract address format: %s\n", contract_address.c_str());
- return 1;
+ printf("ERROR: Invalid contract address format: %s\n",
+ contract_address.c_str());
+ return 1;
}
printf(
@@ -205,31 +206,30 @@ int main(int argc, char** argv) {
ExecuteContract(&client, caller_address, contract_address, func_name,
func_params);
- }
- else if (cmd == "get_balance") {
+ } else if (cmd == "get_balance") {
std::string address = GetValue(js, "address");
// Validate address format
if (!IsValidAddress(address)) {
- printf("ERROR: Invalid address format: %s\n", address.c_str());
- return 1;
+ printf("ERROR: Invalid address format: %s\n", address.c_str());
+ return 1;
}
auto balance_or = client.GetBalance(address);
- printf("get address %s balance %s\n", address.c_str(), (*balance_or).c_str());
+ printf("get address %s balance %s\n", address.c_str(),
+ (*balance_or).c_str());
} else if (cmd == "set_balance") {
std::string address = GetValue(js, "address");
std::string balance = GetValue(js, "balance");
// Validate address format
if (!IsValidAddress(address)) {
- printf("ERROR: Invalid address format: %s\n", address.c_str());
- return 1;
+ printf("ERROR: Invalid address format: %s\n", address.c_str());
+ return 1;
}
printf("address %s balance %s\n", address.c_str(), balance.c_str());
auto ret = client.SetBalance(address, balance);
- printf("set address %s balance %s ret %s\n", address.c_str(), balance.c_str(), (*ret).c_str());
+ printf("set address %s balance %s ret %s\n", address.c_str(),
+ balance.c_str(), (*ret).c_str());
}
-
}
-
diff --git a/third_party/BUILD b/third_party/BUILD
index 9a1b0d01..8d2b1b8a 100644
--- a/third_party/BUILD
+++ b/third_party/BUILD
@@ -57,5 +57,3 @@ cc_library(
"@com_crowcpp_crow//:crow",
],
)
-
-
diff --git a/tools/generate_region_config.py b/tools/generate_region_config.py
index c3d001f2..417499b8 100644
--- a/tools/generate_region_config.py
+++ b/tools/generate_region_config.py
@@ -81,4 +81,5 @@ if __name__ == "__main__":
template_config = None
if len(sys.argv)>3:
template_config = sys.argv[3]
+ print("generate json config:",template_config)
GenerateJsonConfig(sys.argv[1], sys.argv[2], template_config)