Skip to content

Commit

Permalink
Add options for create_snapshot API (#565)
Browse files Browse the repository at this point in the history
* The only current option is to serialize commits to ensure that
snapshots are created using the latest log index.
  • Loading branch information
greensky00 authored Jan 21, 2025
1 parent ed1c153 commit cf80969
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
23 changes: 22 additions & 1 deletion include/libnuraft/raft_server.hxx
Original file line number Diff line number Diff line change
Expand Up @@ -814,16 +814,37 @@ public:
*/
void notify_log_append_completion(bool ok);

/**
* Options for manual snapshot creation.
*/
struct create_snapshot_options {
create_snapshot_options()
: serialize_commit_(false)
{}
/**
* If `true`, the background commit will be blocked until `create_snapshot`
* returns. However, it will not block the commit for the entire duration
* of the snapshot creation process, as long as your state machine creates
* the snapshot asynchronously.
*
* The purpose of this flag is to ensure that the log index used for
* the snapshot creation is the most recent one.
*/
bool serialize_commit_;
};

/**
* Manually create a snapshot based on the latest committed
* log index of the state machine.
*
* Note that snapshot creation will fail immediately if the previous
* snapshot task is still running.
*
* @params options Options for snapshot creation.
* @return Log index number of the created snapshot or`0` if failed.
*/
ulong create_snapshot();
ulong create_snapshot(const create_snapshot_options& options =
create_snapshot_options());

/**
* Manually and asynchronously create a snapshot on the next earliest
Expand Down
17 changes: 13 additions & 4 deletions src/handle_commit.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -464,10 +464,19 @@ bool raft_server::apply_config_log_entry(ptr<log_entry>& le,
return true;
}

ulong raft_server::create_snapshot() {
uint64_t committed_idx = sm_commit_index_;
p_in("manually create a snapshot on %" PRIu64 "", committed_idx);
return snapshot_and_compact(committed_idx, true) ? committed_idx : 0;
ulong raft_server::create_snapshot(const create_snapshot_options& options) {
auto exec_internal = [&]() {
uint64_t committed_idx = sm_commit_index_;
p_in("manually create a snapshot on %" PRIu64 "", committed_idx);
return snapshot_and_compact(committed_idx, true) ? committed_idx : 0;
};

if (options.serialize_commit_) {
auto_lock(commit_lock_);
return exec_internal();
} else {
return exec_internal();
}
}

ptr< cmd_result<uint64_t> > raft_server::schedule_snapshot_creation() {
Expand Down

0 comments on commit cf80969

Please sign in to comment.