Unverified Commit 004c63e5 authored by Shaya Potter's avatar Shaya Potter Committed by GitHub
Browse files

when become leader by default (only voting node) have to increase term (#11)

major bug in terms of election as term wasn't being increased in cases of partioned network where a demote was received but not applied.

+ adds an assert to the existing test of promotion to leader if only voter to ensure term is incremented as fixed by this PR
parent a2b16dae
...@@ -251,12 +251,17 @@ int raft_periodic(raft_server_t* me_, int msec_since_last_period) ...@@ -251,12 +251,17 @@ int raft_periodic(raft_server_t* me_, int msec_since_last_period)
me->timeout_elapsed += msec_since_last_period; me->timeout_elapsed += msec_since_last_period;
/* Only one voting node means it's safe for us to become the leader */ /* Only one voting node means it's safe for us to become the leader */
if (1 == raft_get_num_voting_nodes(me_) && if ((1 == raft_get_num_voting_nodes(me_)) && raft_node_is_voting(raft_get_my_node(me_)) && !raft_is_leader(me_)) {
raft_node_is_voting(raft_get_my_node((void*)me)) && int e = raft_set_current_term(me_, raft_get_current_term(me_) + 1);
!raft_is_leader(me_)) { if (e != 0) {
int e = raft_become_leader(me_); return e;
if (e != 0) }
return e;
e = raft_become_leader(me_);
if (e != 0) {
return e;
}
// need to update term on new leadership
} }
if (me->state == RAFT_STATE_LEADER) if (me->state == RAFT_STATE_LEADER)
......
#include <stdbool.h> #include <stdbool.h>
#include <assert.h> #include <assert.h>
#include <stdlib.h> #include <stdlib.h>
...@@ -505,11 +504,13 @@ void TestRaft_server_election_timeout_does_promote_us_to_leader_if_there_is_only ...@@ -505,11 +504,13 @@ void TestRaft_server_election_timeout_does_promote_us_to_leader_if_there_is_only
void *r = raft_new(); void *r = raft_new();
raft_add_node(r, NULL, 1, 1); raft_add_node(r, NULL, 1, 1);
raft_set_election_timeout(r, 1000); raft_set_election_timeout(r, 1000);
raft_term_t old_term = raft_get_current_term(r);
/* clock over (ie. 1000 + 1), causing new election */ /* clock over (ie. 1000 + 1), causing new election */
raft_periodic(r, 1001); raft_periodic(r, 1001);
CuAssertTrue(tc, 1 == raft_is_leader(r)); CuAssertTrue(tc, 1 == raft_is_leader(r));
CuAssertTrue(tc, old_term + 1 == raft_get_current_term(r));
} }
void TestRaft_server_election_timeout_does_promote_us_to_leader_if_there_is_only_1_voting_node(CuTest * tc) void TestRaft_server_election_timeout_does_promote_us_to_leader_if_there_is_only_1_voting_node(CuTest * tc)
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment