From ba41d02170b1fc50c1cfa274823fcdc4e6f2adaf Mon Sep 17 00:00:00 2001 From: JackyWoo Date: Tue, 7 Nov 2023 10:22:26 +0800 Subject: [PATCH] Add a new API to reset the whole state machine --- examples/calculator/calc_state_machine.hxx | 6 ++++++ examples/echo/echo_state_machine.hxx | 6 ++++++ include/libnuraft/state_machine.hxx | 6 ++++++ src/handle_snapshot_sync.cxx | 2 ++ 4 files changed, 20 insertions(+) diff --git a/examples/calculator/calc_state_machine.hxx b/examples/calculator/calc_state_machine.hxx index c1574742..96160efb 100644 --- a/examples/calculator/calc_state_machine.hxx +++ b/examples/calculator/calc_state_machine.hxx @@ -179,6 +179,8 @@ public: ptr ctx = entry->second; cur_value_ = ctx->value_; + // Now the last committed_idx is the snapshot's last log index. + last_committed_idx_ = s.get_last_log_idx(); return true; } @@ -213,6 +215,10 @@ public: } } + void reset() override { + cur_value_ = 0; + } + int64_t get_current_value() const { return cur_value_; } private: diff --git a/examples/echo/echo_state_machine.hxx b/examples/echo/echo_state_machine.hxx index 885d0228..6a7557a5 100644 --- a/examples/echo/echo_state_machine.hxx +++ b/examples/echo/echo_state_machine.hxx @@ -110,6 +110,8 @@ public: ptr snp_buf = s.serialize(); last_snapshot_ = snapshot::deserialize(*snp_buf); } + // Now the last committed_idx is the snapshot's last log index. + last_committed_idx_ = s.get_last_log_idx(); return true; } @@ -140,6 +142,10 @@ public: when_done(ret, except); } + void reset() override { + // echo state machine has no state to reset. + } + private: // Last committed Raft log number. std::atomic last_committed_idx_; diff --git a/include/libnuraft/state_machine.hxx b/include/libnuraft/state_machine.hxx index ca326849..356def18 100644 --- a/include/libnuraft/state_machine.hxx +++ b/include/libnuraft/state_machine.hxx @@ -327,6 +327,12 @@ public: */ virtual bool allow_leadership_transfer() { return true; } + /** + * Reset the state machine clearing all data and related state, + * should be invoked before follower apply snapshot from leader. + */ + virtual void reset(){}; + /** * Parameters for `adjust_commit_index` API. */ diff --git a/src/handle_snapshot_sync.cxx b/src/handle_snapshot_sync.cxx index 8165cd14..d3804a68 100644 --- a/src/handle_snapshot_sync.cxx +++ b/src/handle_snapshot_sync.cxx @@ -559,6 +559,8 @@ bool raft_server::handle_snapshot_sync_req(snapshot_sync_req& req, std::unique_l stop_election_timer(); p_in("successfully compact the log store, will now ask the " "statemachine to apply the snapshot"); + p_in("firstly reset the statemachine"); + state_machine_->reset(); if (!state_machine_->apply_snapshot(req.get_snapshot())) { // LCOV_EXCL_START p_er("failed to apply the snapshot after log compacted, "