[PATCH v2] election: Add a possible callback when becoming a follower
Export this patch
Signed-off-by: Louis Solofrizzo <lsolofrizzo@scaleway.com>
---
libfloat.h | 7 +++++++
raft.c | 14 +++++++++++++-
2 files changed, 20 insertions(+), 1 deletion(-)
diff --git a/libfloat.h b/libfloat.h
index e5494b7..cfaa156 100644
--- a/libfloat.h
+++ b/libfloat.h
@@ -105,6 +105,13 @@ struct libfloat_ctx_s {
*/
void (*become_leader_cb)(struct libfloat_ctx_s *);
+ /*!
+ * \brief Callback when becoming follower of a cluster
+ *
+ * \param[in] struct libfloat_ctx_s * - Cluster context
+ */
+ void (*become_follower_cb)(struct libfloat_ctx_s *);
+
/*!
* \brief Send a "is leader healthy" to a node
*
diff --git a/raft.c b/raft.c
index 8f10661..8148c96 100644
--- a/raft.c
+++ b/raft.c
@@ -36,11 +36,23 @@ void __libfloat_become_candidate(libfloat_ctx_t *ctx, libfloat_elections_args_t
void __libfloat_become_follower(libfloat_ctx_t *ctx, libfloat_elections_args_t *args)
{
+ if (ctx->state == RAFT_STATE_FOLLOWER)
+ return;
+
+ if (ctx->become_follower_cb != NULL && ctx->state == RAFT_STATE_LEADER)
+ {
+ /* Only call this when we loose leadership */
+ ctx->become_follower_cb(ctx);
+ }
+
+ ctx->state = RAFT_STATE_FOLLOWER;
+
DEBUG(ctx, "Becoming follower: reason=%s", args->reason);
ctx->abort_send_snapshot(ctx);
- ctx->state = RAFT_STATE_FOLLOWER;
+
ctx->election_timeout_rand = ctx->conf.election_timeout + ctx->rand() % ctx->conf.election_timeout;
ctx->stat.leader_election_time = 0;
+
libfloat_vote_for(ctx, 0);
}
--
2.38.1