[Tarantool-patches] [PATCH v2 3/4] raft: check box_raft is inited before usage

Vladislav Shpilevoy v.shpilevoy at tarantool.org
Tue Nov 10 02:58:53 MSK 2020


Since box_raft is now initialized at runtime and is used from
several subsystems (memtx for snapshots; applier for accepting
rows; box.info for monitoring), it may be easy to screw the
intialization order and accidentally use the not initialized
global raft object.

This patch adds a sanity check ensuring it does not happen. The
raft state is set to 0 at program start. Then any access to the
global raft object firstly checks the state not being 0.

The initialization order will get trickier when raft will stop
using globals from replication and from box, and will be used from
them more extensively.

Part of #5303
---
 src/box/raft.c | 12 +++++++++++-
 src/box/raft.h |  6 ++++++
 2 files changed, 17 insertions(+), 1 deletion(-)

diff --git a/src/box/raft.c b/src/box/raft.c
index ef93d3d99..0abeb5f5d 100644
--- a/src/box/raft.c
+++ b/src/box/raft.c
@@ -44,7 +44,13 @@
  */
 #define RAFT_RANDOM_ELECTION_FACTOR 0.1
 
-struct raft box_raft_global;
+struct raft box_raft_global = {
+	/*
+	 * Set an invalid state to validate in runtime the global raft node is
+	 * not used before initialization.
+	 */
+	.state = 0,
+};
 
 /**
  * When decoding we should never trust that there is
@@ -1114,4 +1120,8 @@ box_raft_free(void)
 	 */
 	box_raft_global.worker = NULL;
 	raft_destroy(&box_raft_global);
+	/*
+	 * Invalidate so as box_raft() would fail if any usage attempt happens.
+	 */
+	box_raft_global.state = 0;
 }
diff --git a/src/box/raft.h b/src/box/raft.h
index 18ba0f7dc..83a20f670 100644
--- a/src/box/raft.h
+++ b/src/box/raft.h
@@ -31,6 +31,7 @@
  */
 #include <stdint.h>
 #include <stdbool.h>
+#include <assert.h>
 #include "tarantool_ev.h"
 #include "trigger.h"
 
@@ -275,6 +276,11 @@ static inline struct raft *
 box_raft(void)
 {
 	extern struct raft box_raft_global;
+	/**
+	 * Ensure the raft node can be used. I.e. that it is properly
+	 * initialized. Entirely for debug purposes.
+	 */
+	assert(box_raft_global.state != 0);
 	return &box_raft_global;
 }
 
-- 
2.21.1 (Apple Git-122.3)



More information about the Tarantool-patches mailing list