emqx_plugin_libs_pool.erl 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2021 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_plugin_libs_pool).
  17. -export([ start_pool/3
  18. , stop_pool/1
  19. , pool_name/1
  20. , health_check/3
  21. ]).
  22. pool_name(ID) when is_binary(ID) ->
  23. list_to_atom(binary_to_list(ID)).
  24. start_pool(Name, Mod, Options) ->
  25. case ecpool:start_sup_pool(Name, Mod, Options) of
  26. {ok, _} -> logger:log(info, "Initiated ~0p Successfully", [Name]);
  27. {error, {already_started, _Pid}} ->
  28. stop_pool(Name),
  29. start_pool(Name, Mod, Options);
  30. {error, Reason} ->
  31. logger:log(error, "Initiate ~0p failed ~0p", [Name, Reason]),
  32. error({start_pool_failed, Name})
  33. end.
  34. stop_pool(Name) ->
  35. case ecpool:stop_sup_pool(Name) of
  36. ok -> logger:log(info, "Destroyed ~0p Successfully", [Name]);
  37. {error, not_found} -> ok;
  38. {error, Reason} ->
  39. logger:log(error, "Destroy ~0p failed, ~0p", [Name, Reason]),
  40. error({stop_pool_failed, Name})
  41. end.
  42. health_check(PoolName, CheckFunc, State) when is_function(CheckFunc) ->
  43. Status = [begin
  44. case ecpool_worker:client(Worker) of
  45. {ok, Conn} -> CheckFunc(Conn);
  46. _ -> false
  47. end
  48. end || {_WorkerName, Worker} <- ecpool:workers(PoolName)],
  49. case length(Status) > 0 andalso lists:all(fun(St) -> St =:= true end, Status) of
  50. true -> {ok, State};
  51. false -> {error, test_query_failed, State}
  52. end.