pooler_sup.erl 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. -module(pooler_sup).
  2. -behaviour(supervisor).
  3. -export([init/1,
  4. new_pool/1,
  5. rm_pool/1,
  6. pool_child_spec/1,
  7. start_link/0]).
  8. -include("pooler.hrl").
  9. start_link() ->
  10. supervisor:start_link({local, ?MODULE}, ?MODULE, []).
  11. init([]) ->
  12. %% a list of pool configs
  13. Config = case application:get_env(pooler, pools) of
  14. {ok, C} ->
  15. C;
  16. undefined ->
  17. []
  18. end,
  19. MetricsConfig = {metrics_mod, metrics_module()},
  20. Pools = [ pooler_config:list_to_pool([MetricsConfig | L]) || L <- Config ],
  21. PoolSupSpecs = [ pool_sup_spec(Pool) || Pool <- Pools ],
  22. ets:new(?POOLER_GROUP_TABLE, [set, public, named_table, {write_concurrency, true}]),
  23. {ok, {{one_for_one, 5, 60}, [starter_sup_spec() | PoolSupSpecs]}}.
  24. %% @doc Create a new pool from proplist pool config `PoolConfig'. The
  25. %% public API for this functionality is {@link pooler:new_pool/1}.
  26. new_pool(PoolConfig) ->
  27. Spec = pool_child_spec(PoolConfig),
  28. supervisor:start_child(?MODULE, Spec).
  29. %% @doc Create a child spec for new pool from proplist pool config `PoolConfig'. The
  30. %% public API for this functionality is {@link pooler:pool_child_spec/1}.
  31. pool_child_spec(PoolConfig) ->
  32. MetricsConfig = {metrics_mod, metrics_module()},
  33. NewPool = pooler_config:list_to_pool([MetricsConfig | PoolConfig]),
  34. pool_sup_spec(NewPool).
  35. %% @doc Shutdown the named pool.
  36. rm_pool(Name) ->
  37. SupName = pool_sup_name(Name),
  38. case supervisor:terminate_child(?MODULE, SupName) of
  39. {error, not_found} ->
  40. ok;
  41. ok ->
  42. supervisor:delete_child(?MODULE, SupName);
  43. Error ->
  44. Error
  45. end.
  46. starter_sup_spec() ->
  47. {pooler_starter_sup, {pooler_starter_sup, start_link, []},
  48. transient, 5000, supervisor, [pooler_starter_sup]}.
  49. pool_sup_spec(#pool{name = Name} = Pool) ->
  50. SupName = pool_sup_name(Name),
  51. {SupName, {pooler_pool_sup, start_link, [Pool]},
  52. transient, 5000, supervisor, [pooler_pool_sup]}.
  53. pool_sup_name(Name) ->
  54. list_to_atom("pooler_" ++ atom_to_list(Name) ++ "_pool_sup").
  55. metrics_module() ->
  56. case application:get_env(pooler, metrics_module) of
  57. {ok, Mod} ->
  58. Mod;
  59. undefined ->
  60. pooler_no_metrics
  61. end.