Skip to content
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

Open
wants to merge 25 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
2051a9d
Raft leader election in progress
lnikon Dec 24, 2024
10396a7
Implement leader election
lnikon Dec 28, 2024
b9b5995
Refactor timer thread
lnikon Dec 28, 2024
614c2bc
A little refactoring
lnikon Dec 29, 2024
2e6374a
Refactor into separate headers & fix bugs
lnikon Dec 29, 2024
e0a354b
Implement coderabbit reviews #1
lnikon Dec 30, 2024
2fa9fca
Fix PR reviews & bugs #2
lnikon Dec 31, 2024
0832944
Fix PR reviews #3
lnikon Dec 31, 2024
2b7359e
Refactor election thread & implement log replication
lnikon Jan 2, 2025
f53b501
Fix state machine modification during log replication
lnikon Jan 3, 2025
497b88d
Implement persistence
lnikon Jan 7, 2025
ee68090
Fix docker image build errors & Implement CR suggestions
lnikon Jan 9, 2025
f68e8d1
Implement CR suggestions
lnikon Jan 9, 2025
3372412
Implement CR suggestions
lnikon Jan 9, 2025
1b8b93b
BestPractice improvement
lnikon Jan 9, 2025
ff8edca
Check fstream failures when persisting raft's state & code style changes
lnikon Jan 11, 2025
7ca37a9
Support dependency injection for raft classes & prepare for mock testing
lnikon Jan 12, 2025
54f02c9
Graceful shutdown in progress
lnikon Jan 14, 2025
d803bec
Bug fixes
lnikon Jan 15, 2025
9d5cd21
Remove unused headers
lnikon Jan 15, 2025
d63a8fe
Graceful shutdown in progress
lnikon Jan 18, 2025
0bab68f
Implement graceful shutdown
lnikon Jan 22, 2025
ece39ad
Add unit test for leader election
lnikon Jan 22, 2025
0834c89
Fix unsynced access to heartbeat atomic
lnikon Jan 23, 2025
cb376b9
Add new unit test
lnikon Jan 25, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 28 additions & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,33 @@
// 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"
}
},
Comment on lines +7 to +33
Copy link

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:

  1. Add build task to ensure RaftMain is compiled
  2. Add command line arguments for Raft configuration (node ID, peer list)
  3. Make debug port configurable to avoid conflicts

Apply this diff:

         {
             "name": "rr - RaftMain",
             "type": "cppdbg",
             "request": "launch",
             "program": "${workspaceFolder}/build/RaftMain",
-            "miDebuggerServerAddress": "localhost:50505",
+            "miDebuggerServerAddress": "localhost:${input:debugPort}",
+            "args": [
+                "--node-id", "${input:nodeId}",
+                "--config", "${workspaceFolder}/assets/raft_config.json"
+            ],
             "stopAtEntry": false,
             "cwd": "${workspaceFolder}",
             "environment": [],
             "externalConsole": true,
+            "preLaunchTask": "build",
             "linux": {
                 "MIMode": "gdb",

Add to the end of the file:

    "inputs": [
        {
            "id": "debugPort",
            "type": "promptString",
            "description": "Debug port for remote debugging",
            "default": "50505"
        },
        {
            "id": "nodeId",
            "type": "promptString",
            "description": "Raft node ID",
            "default": "1"
        }
    ]

{
"name": "Debug - LSMTreeTest",
"type": "cppdbg",
Expand Down Expand Up @@ -84,7 +111,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": [],
Expand Down
4 changes: 2 additions & 2 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED On)
set(CMAKE_CXX_EXTENSIONS Off)

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra -pedantic-errors")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -pedantic-errors")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra -Wthread-safety -pedantic-errors")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wthread-safety -pedantic-errors")
lnikon marked this conversation as resolved.
Show resolved Hide resolved

set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}")
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}")
Expand Down
1 change: 1 addition & 0 deletions examples/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ project(zkv)

add_subdirectory(absl)
add_subdirectory(embedded)
add_subdirectory(raft)
6 changes: 6 additions & 0 deletions examples/raft/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
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)
70 changes: 70 additions & 0 deletions examples/raft/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
#include <random>

#include "raft.h"

#include <grpcpp/server.h>

#include <cxxopts.hpp>

#include <spdlog/spdlog.h>

auto generateRandomTimeout() -> int
{
const int minTimeout{150};
const int maxTimeout{300};

std::random_device randomDevice;
std::mt19937 gen(randomDevice());
std::uniform_int_distribution<> dist(minTimeout, maxTimeout);

return dist(gen);
}

int main(int argc, char *argv[])
{
cxxopts::Options options("raft");
options.add_options()("id", "id of the node", cxxopts::value<ID>())(
"nodes", "ip addresses of replicas in a correct order", cxxopts::value<std::vector<IP>>());

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>();
auto nodeIps = parsedOptions["nodes"].as<std::vector<IP>>();
for (auto ip : nodeIps)
{
spdlog::info(ip);
}

spdlog::info("nodeIps.size()={}", nodeIps.size());

if (nodeId == 0)
{
spdlog::error("ID of the node should be positve integer");
return EXIT_FAILURE;
}

if (nodeIps.empty())
{
spdlog::error("List of node IPs can't be empty");
return EXIT_FAILURE;
}

ConsensusModule cm(nodeId, nodeIps);
if (!cm.init())
{
spdlog::error("Failed to initialize the state machine");
return EXIT_FAILURE;
}

cm.start();

cm.stop();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Implement graceful shutdown handling.

The server should handle SIGTERM/SIGINT signals for graceful shutdown instead of immediate stop.

void signal_handler(int signal) {
    spdlog::info("Received signal {}. Initiating graceful shutdown...", signal);
    // Trigger graceful shutdown
}

// In main():
std::signal(SIGTERM, signal_handler);
std::signal(SIGINT, signal_handler);


return EXIT_SUCCESS;
}
Loading
Loading