Skip to content

Commit 5ad9c14

Browse files
authored
Merge pull request #337 from rabbitmq/protect-writes-to-PT_STORE_IDS-with-locks
khepri_cluster: Acquire lock before doing a read/modify/write on ?PT_STORE_IDS
2 parents b1783bb + 2e2ff90 commit 5ad9c14

File tree

1 file changed

+25
-10
lines changed

1 file changed

+25
-10
lines changed

src/khepri_cluster.erl

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1468,11 +1468,17 @@ complete_ra_server_config(#{cluster_name := StoreId,
14681468

14691469
remember_store(RaSystem, #{cluster_name := StoreId} = RaServerConfig) ->
14701470
?assert(maps:is_key(id, RaServerConfig)),
1471-
StoreIds = persistent_term:get(?PT_STORE_IDS, #{}),
1472-
Props = #{ra_system => RaSystem,
1473-
ra_server_config => RaServerConfig},
1474-
StoreIds1 = StoreIds#{StoreId => Props},
1475-
persistent_term:put(?PT_STORE_IDS, StoreIds1),
1471+
Lock = store_ids_lock(),
1472+
global:set_lock(Lock, [node()]),
1473+
try
1474+
StoreIds = persistent_term:get(?PT_STORE_IDS, #{}),
1475+
Props = #{ra_system => RaSystem,
1476+
ra_server_config => RaServerConfig},
1477+
StoreIds1 = StoreIds#{StoreId => Props},
1478+
persistent_term:put(?PT_STORE_IDS, StoreIds1)
1479+
after
1480+
global:del_lock(Lock, [node()])
1481+
end,
14761482
ok.
14771483

14781484
-spec get_store_prop(StoreId, PropName) -> Ret when
@@ -1502,14 +1508,23 @@ get_store_prop(StoreId, PropName) ->
15021508

15031509
forget_store(StoreId) ->
15041510
ok = khepri_machine:clear_cache(StoreId),
1505-
StoreIds = persistent_term:get(?PT_STORE_IDS, #{}),
1506-
StoreIds1 = maps:remove(StoreId, StoreIds),
1507-
case maps:size(StoreIds1) of
1508-
0 -> _ = persistent_term:erase(?PT_STORE_IDS);
1509-
_ -> ok = persistent_term:put(?PT_STORE_IDS, StoreIds1)
1511+
Lock = store_ids_lock(),
1512+
global:set_lock(Lock, [node()]),
1513+
try
1514+
StoreIds = persistent_term:get(?PT_STORE_IDS, #{}),
1515+
StoreIds1 = maps:remove(StoreId, StoreIds),
1516+
case maps:size(StoreIds1) of
1517+
0 -> _ = persistent_term:erase(?PT_STORE_IDS);
1518+
_ -> ok = persistent_term:put(?PT_STORE_IDS, StoreIds1)
1519+
end
1520+
after
1521+
global:del_lock(Lock, [node()])
15101522
end,
15111523
ok.
15121524

1525+
store_ids_lock() ->
1526+
{?PT_STORE_IDS, self()}.
1527+
15131528
-spec get_store_ids() -> [StoreId] when
15141529
StoreId :: khepri:store_id().
15151530
%% @doc Returns the list of running stores.

0 commit comments

Comments
 (0)