emqx_cm_locker.erl 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved.
  3. %%
  4. %% Licensed under the Apache License, Version 2.0 (the "License");
  5. %% you may not use this file except in compliance with the License.
  6. %% You may obtain a copy of the License at
  7. %%
  8. %% http://www.apache.org/licenses/LICENSE-2.0
  9. %%
  10. %% Unless required by applicable law or agreed to in writing, software
  11. %% distributed under the License is distributed on an "AS IS" BASIS,
  12. %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. %% See the License for the specific language governing permissions and
  14. %% limitations under the License.
  15. %%--------------------------------------------------------------------
  16. -module(emqx_cm_locker).
  17. -include("emqx.hrl").
  18. -include("types.hrl").
  19. -export([start_link/0]).
  20. -export([ trans/2
  21. , trans/3
  22. , lock/1
  23. , lock/2
  24. , unlock/1
  25. ]).
  26. -spec(start_link() -> startlink_ret()).
  27. start_link() ->
  28. ekka_locker:start_link(?MODULE).
  29. -spec(trans(emqx_types:clientid(), fun(([node()]) -> any())) -> any()).
  30. trans(ClientId, Fun) ->
  31. trans(ClientId, Fun, undefined).
  32. -spec(trans(maybe(emqx_types:clientid()),
  33. fun(([node()])-> any()), ekka_locker:piggyback()) -> any()).
  34. trans(undefined, Fun, _Piggyback) ->
  35. Fun([]);
  36. trans(ClientId, Fun, Piggyback) ->
  37. case lock(ClientId, Piggyback) of
  38. {true, Nodes} ->
  39. try Fun(Nodes) after unlock(ClientId) end;
  40. {false, _Nodes} ->
  41. {error, client_id_unavailable}
  42. end.
  43. -spec(lock(emqx_types:clientid()) -> ekka_locker:lock_result()).
  44. lock(ClientId) ->
  45. ekka_locker:acquire(?MODULE, ClientId, strategy()).
  46. -spec(lock(emqx_types:clientid(), ekka_locker:piggyback()) -> ekka_locker:lock_result()).
  47. lock(ClientId, Piggyback) ->
  48. ekka_locker:acquire(?MODULE, ClientId, strategy(), Piggyback).
  49. -spec(unlock(emqx_types:clientid()) -> {boolean(), [node()]}).
  50. unlock(ClientId) ->
  51. ekka_locker:release(?MODULE, ClientId, strategy()).
  52. -spec(strategy() -> local | leader | quorum | all).
  53. strategy() ->
  54. emqx:get_env(session_locking_strategy, quorum).