-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Implement Raft protocol to replicate KV pairs #10
base: master
Are you sure you want to change the base?
Changes from 24 commits
2051a9d
10396a7
b9b5995
614c2bc
2e6374a
e0a354b
2fa9fca
0832944
2b7359e
f53b501
497b88d
ee68090
f68e8d1
3372412
1b8b93b
ff8edca
7ca37a9
54f02c9
d803bec
9d5cd21
d63a8fe
0bab68f
ece39ad
0834c89
cb376b9
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
|
@@ -4,6 +4,105 @@ | |||||||||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 | ||||||||||||
"version": "0.2.0", | ||||||||||||
"configurations": [ | ||||||||||||
{ | ||||||||||||
"name": "rr - RaftMain", | ||||||||||||
"type": "cppdbg", | ||||||||||||
"request": "launch", | ||||||||||||
"program": "${workspaceFolder}/build/RaftMain", | ||||||||||||
"miDebuggerServerAddress": "localhost:50505", | ||||||||||||
"stopAtEntry": false, | ||||||||||||
"cwd": "${workspaceFolder}", | ||||||||||||
"environment": [], | ||||||||||||
"externalConsole": true, | ||||||||||||
"linux": { | ||||||||||||
"MIMode": "gdb", | ||||||||||||
"setupCommands": [ | ||||||||||||
{ | ||||||||||||
"description": "Setup to resolve symbols", | ||||||||||||
"text": "set sysroot /", | ||||||||||||
"ignoreFailures": false | ||||||||||||
} | ||||||||||||
] | ||||||||||||
}, | ||||||||||||
"osx": { | ||||||||||||
"MIMode": "gdb" | ||||||||||||
}, | ||||||||||||
"windows": { | ||||||||||||
"MIMode": "gdb" | ||||||||||||
} | ||||||||||||
}, | ||||||||||||
{ | ||||||||||||
"name": "Debug - RaftMain", | ||||||||||||
"type": "cppdbg", | ||||||||||||
"request": "launch", | ||||||||||||
"program": "${workspaceFolder}/build/RaftMain", // Path to the compiled executable | ||||||||||||
"args": [ | ||||||||||||
"--id", | ||||||||||||
"1", | ||||||||||||
"--nodes", | ||||||||||||
"0.0.0.0:8080,0.0.0.0:8081,0.0.0.0:8082" | ||||||||||||
], // Arguments to pass to the program | ||||||||||||
"stopAtEntry": false, // Set to true to stop at the program's entry point | ||||||||||||
"cwd": "${workspaceFolder}", // Current working directory | ||||||||||||
"environment": [], | ||||||||||||
"externalConsole": false, // Set to true if you want to use an external terminal | ||||||||||||
"MIMode": "gdb", // Use "lldb" if you're using clang on macOS | ||||||||||||
"setupCommands": [ | ||||||||||||
{ | ||||||||||||
"description": "Enable pretty-printing for gdb", | ||||||||||||
"text": "-enable-pretty-printing", | ||||||||||||
"ignoreFailures": true | ||||||||||||
} | ||||||||||||
], | ||||||||||||
"preLaunchTask": "build", // Ensure your program is built before launching | ||||||||||||
"miDebuggerPath": "/usr/bin/gdb", // Path to the gdb or lldb debugger | ||||||||||||
"logging": { | ||||||||||||
"trace": true, // Enable trace for debugging the launch.json config | ||||||||||||
"traceResponse": true, | ||||||||||||
"engineLogging": false | ||||||||||||
}, | ||||||||||||
"launchCompleteCommand": "exec-run", | ||||||||||||
"targetArchitecture": "x86_64", | ||||||||||||
"pipeTransport": { | ||||||||||||
"pipeCwd": "", | ||||||||||||
"pipeProgram": "/bin/bash", | ||||||||||||
"pipeArgs": [ | ||||||||||||
"-c" | ||||||||||||
], | ||||||||||||
"debuggerPath": "/usr/bin/gdb" | ||||||||||||
}, | ||||||||||||
}, | ||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fix JSON syntax errors Remove trailing commas after the pipeTransport objects: "pipeTransport": {
// ...
"debuggerPath": "/usr/bin/gdb"
- },
+ }
}, Also applies to: 105-105 🧰 Tools🪛 Biome (1.9.4)[error] 74-74: Expected a property but instead found '}'. Expected a property here. (parse) |
||||||||||||
{ | ||||||||||||
"name": "Debug Attach - RaftMain", | ||||||||||||
"type": "cppdbg", | ||||||||||||
"request": "attach", | ||||||||||||
"program": "${workspaceFolder}/build/RaftMain", // Path to the compiled executable | ||||||||||||
"processId": "${command:pickProcess}", | ||||||||||||
"MIMode": "gdb", // Use "lldb" if you're using clang on macOS | ||||||||||||
"setupCommands": [ | ||||||||||||
{ | ||||||||||||
"description": "Enable pretty-printing for gdb", | ||||||||||||
"text": "-enable-pretty-printing", | ||||||||||||
"ignoreFailures": true | ||||||||||||
} | ||||||||||||
], | ||||||||||||
"preLaunchTask": "build", // Ensure your program is built before launching | ||||||||||||
"miDebuggerPath": "/usr/bin/gdb", // Path to the gdb or lldb debugger | ||||||||||||
"logging": { | ||||||||||||
"trace": true, // Enable trace for debugging the launch.json config | ||||||||||||
"traceResponse": true, | ||||||||||||
"engineLogging": false | ||||||||||||
}, | ||||||||||||
"targetArchitecture": "x86_64", | ||||||||||||
"pipeTransport": { | ||||||||||||
"pipeCwd": "", | ||||||||||||
"pipeProgram": "/bin/bash", | ||||||||||||
"pipeArgs": [ | ||||||||||||
"-c" | ||||||||||||
], | ||||||||||||
"debuggerPath": "/usr/bin/gdb" | ||||||||||||
}, | ||||||||||||
}, | ||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fix JSON syntax error Remove the trailing comma after the pipeTransport object. Apply this diff: ],
"debuggerPath": "/usr/bin/gdb"
- },
+ }
}, 📝 Committable suggestion
Suggested change
🧰 Tools🪛 Biome (1.9.4)[error] 64-64: Expected a property but instead found '}'. Expected a property here. (parse) |
||||||||||||
{ | ||||||||||||
"name": "Debug - LSMTreeTest", | ||||||||||||
"type": "cppdbg", | ||||||||||||
|
@@ -84,7 +183,7 @@ | |||||||||||
"args": [ | ||||||||||||
"-c", | ||||||||||||
"./assets/tkvpp_config.json" | ||||||||||||
], // Arguments to pass to the program | ||||||||||||
], | ||||||||||||
"stopAtEntry": false, // Set to true to stop at the program's entry point | ||||||||||||
"cwd": "${workspaceFolder}", // Current working directory | ||||||||||||
"environment": [], | ||||||||||||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,3 +3,4 @@ project(zkv) | |
|
||
add_subdirectory(absl) | ||
add_subdirectory(embedded) | ||
add_subdirectory(raft) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
cmake_minimum_required(VERSION 3.25) | ||
project(zkv) | ||
|
||
add_executable(RaftMain "main.cpp" "raft.cpp") | ||
set_target_properties(RaftMain PROPERTIES CXX_STANDARD 23) | ||
target_link_libraries(RaftMain PRIVATE DB RaftProtoObjects TKVProtoObjects) | ||
|
||
add_executable(RaftTest "raft_test.cpp" "raft.cpp") | ||
set_target_properties(RaftTest PROPERTIES CXX_STANDARD 23) | ||
target_link_libraries(RaftTest gtest::gtest DB | ||
RaftProtoObjects TKVProtoObjects) | ||
|
||
# Register Catch2 tests with CTest | ||
# include(Catch) | ||
# catch_discover_tests(RaftTest) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
#include <grpcpp/server.h> | ||
#include <grpcpp/security/credentials.h> | ||
|
||
#include "raft.h" | ||
|
||
#include <cxxopts.hpp> | ||
|
||
#include <spdlog/spdlog.h> | ||
|
||
#include <csignal> | ||
|
||
std::condition_variable gCv; | ||
|
||
static void signalHandler(int sig) | ||
{ | ||
if (sig == SIGTERM || sig == SIGINT) | ||
{ | ||
gCv.notify_all(); | ||
} | ||
} | ||
Comment on lines
+14
to
+20
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Critical Issue: Unsafe use of Calling Suggested fix: Use an -std::condition_variable gCv;
-static void signalHandler(int sig)
+std::atomic<bool> gShutdown{false};
+void signalHandler(int sig)
{
if (sig == SIGTERM || sig == SIGINT)
{
- gCv.notify_all();
+ gShutdown.store(true);
}
}
...
- std::mutex mtx;
- std::unique_lock<std::mutex> lock(mtx);
- gCv.wait(lock);
+ while (!gShutdown.load())
+ {
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
+ } This replaces the condition variable with an atomic flag that the main thread can periodically check.
|
||
|
||
auto main(int argc, char *argv[]) -> int | ||
{ | ||
std::signal(SIGTERM, signalHandler); | ||
std::signal(SIGINT, signalHandler); | ||
|
||
cxxopts::Options options("raft"); | ||
options.add_options()("id", "id of the node", cxxopts::value<id_t>())( | ||
"nodes", "ip addresses of replicas in a correct order", cxxopts::value<std::vector<raft::ip_t>>()); | ||
|
||
auto parsedOptions = options.parse(argc, argv); | ||
if ((parsedOptions.count("help") != 0U) || (parsedOptions.count("id") == 0U) || | ||
(parsedOptions.count("nodes") == 0U)) | ||
{ | ||
spdlog::info("{}", options.help()); | ||
return EXIT_SUCCESS; | ||
} | ||
|
||
auto nodeId = parsedOptions["id"].as<id_t>(); | ||
if (nodeId == 0) | ||
{ | ||
spdlog::error("ID of the node should be positve integer"); | ||
return EXIT_FAILURE; | ||
} | ||
|
||
auto nodeIps = parsedOptions["nodes"].as<std::vector<raft::ip_t>>(); | ||
if (nodeIps.empty()) | ||
{ | ||
spdlog::error("List of node IPs can't be empty"); | ||
return EXIT_FAILURE; | ||
} | ||
Comment on lines
+46
to
+51
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion Enhance IP address validation. The current validation only checks if the list is not empty. Consider adding validation for:
Example validation function: bool validateIpAddress(const std::string& ip) {
std::regex ipRegex(
"^(?:[0-9]{1,3}\\.){3}[0-9]{1,3}(:[0-9]{1,5})?$"
);
if (!std::regex_match(ip, ipRegex)) {
return false;
}
// Additional validation for port range and IP octets
return true;
} |
||
|
||
std::vector<raft::raft_node_grpc_client_t> replicas; | ||
for (raft::id_t replicaId{1}; const auto &replicaIp : nodeIps) | ||
{ | ||
if (replicaId != nodeId) | ||
{ | ||
std::unique_ptr<RaftService::Stub> stub{ | ||
RaftService::NewStub(grpc::CreateChannel(replicaIp, grpc::InsecureChannelCredentials()))}; | ||
|
||
replicas.emplace_back(raft::node_config_t{.m_id = replicaId, .m_ip = replicaIp}, std::move(stub)); | ||
} | ||
|
||
++replicaId; | ||
} | ||
|
||
raft::consensus_module_t consensusModule({.m_id = nodeId, .m_ip = nodeIps[nodeId - 1]}, std::move(replicas)); | ||
if (!consensusModule.init()) | ||
{ | ||
spdlog::error("Failed to initialize the state machine"); | ||
return EXIT_FAILURE; | ||
} | ||
Comment on lines
+67
to
+72
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion Enhance consensus module initialization error handling. Add timeout and detailed error reporting for initialization failures. - if (!consensusModule.init())
+ auto initStart = std::chrono::steady_clock::now();
+ while (!consensusModule.init())
{
- spdlog::error("Failed to initialize the state machine");
+ auto elapsed = std::chrono::steady_clock::now() - initStart;
+ if (elapsed > std::chrono::seconds(10)) {
+ spdlog::error("Failed to initialize consensus module after {} seconds",
+ std::chrono::duration_cast<std::chrono::seconds>(elapsed).count());
+ spdlog::error("Last error: {}", consensusModule.getLastError());
+ return EXIT_FAILURE;
+ }
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
+ }
|
||
|
||
spdlog::set_level(spdlog::level::debug); | ||
consensusModule.start(); | ||
|
||
std::mutex mtx; | ||
std::unique_lock<std::mutex> lock(mtx); | ||
gCv.wait(lock); | ||
|
||
consensusModule.stop(); | ||
|
||
return EXIT_SUCCESS; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Enhance RaftMain debug configuration for multi-node debugging.
The configuration needs improvements for debugging multiple Raft nodes:
Apply this diff:
Add to the end of the file: