pooler.erl 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  1. %% @author Seth Falcon <seth@userprimary.net>
  2. %% @copyright 2011-2013 Seth Falcon
  3. %% @doc This is the main interface to the pooler application
  4. %%
  5. %% To integrate with your application, you probably want to call
  6. %% application:start(pooler) after having specified appropriate
  7. %% configuration for the pooler application (either via a config file
  8. %% or appropriate calls to the application module to set the
  9. %% application's config).
  10. %%
  11. -module(pooler).
  12. -behaviour(gen_server).
  13. -include("pooler.hrl").
  14. -include_lib("eunit/include/eunit.hrl").
  15. %% type specs for pool metrics
  16. -type metric_value() :: 'unknown_pid' |
  17. non_neg_integer() |
  18. {'add_pids_failed', non_neg_integer(), non_neg_integer()} |
  19. {'inc',1} |
  20. 'error_no_members'.
  21. -type metric_type() :: 'counter' | 'histogram' | 'history' | 'meter'.
  22. %% ------------------------------------------------------------------
  23. %% API Function Exports
  24. %% ------------------------------------------------------------------
  25. -export([accept_member/2,
  26. start_link/1,
  27. take_member/1,
  28. take_member/2,
  29. take_group_member/1,
  30. return_group_member/2,
  31. return_group_member/3,
  32. return_member/2,
  33. return_member/3,
  34. pool_stats/1,
  35. manual_start/0,
  36. new_pool/1,
  37. pool_child_spec/1,
  38. rm_pool/1,
  39. rm_group/1
  40. ]).
  41. %% ------------------------------------------------------------------
  42. %% gen_server Function Exports
  43. %% ------------------------------------------------------------------
  44. -export([init/1,
  45. handle_call/3,
  46. handle_cast/2,
  47. handle_info/2,
  48. terminate/2,
  49. code_change/3]).
  50. %% To help with testing internal functions
  51. -ifdef(TEST).
  52. -compile([export_all]).
  53. -endif.
  54. %% ------------------------------------------------------------------
  55. %% API Function Definitions
  56. %% ------------------------------------------------------------------
  57. start_link(#pool{name = Name} = Pool) ->
  58. gen_server:start_link({local, Name}, ?MODULE, Pool, []).
  59. manual_start() ->
  60. application:start(sasl),
  61. application:start(pooler).
  62. %% @doc Start a new pool described by the proplist `PoolConfig'. The
  63. %% following keys are required in the proplist:
  64. %%
  65. %% <dl>
  66. %% <dt>`name'</dt>
  67. %% <dd>An atom giving the name of the pool.</dd>
  68. %% <dt>`init_count'</dt>
  69. %% <dd>Number of members to add to the pool at start. When the pool is
  70. %% started, `init_count' members will be started in parallel.</dd>
  71. %% <dt>`max_count'</dt>
  72. %% <dd>Maximum number of members in the pool.</dd>
  73. %% <dt>`start_mfa'</dt>
  74. %% <dd>A tuple of the form `{Mod, Fun, Args}' describing how to start
  75. %% new pool members.</dd>
  76. %% </dl>
  77. %%
  78. %% In addition, you can specify any of the following optional
  79. %% configuration options:
  80. %%
  81. %% <dl>
  82. %% <dt>`group'</dt>
  83. %% <dd>An atom giving the name of the group this pool belongs
  84. %% to. Pools sharing a common `group' value can be accessed using
  85. %% {@link take_group_member/1} and {@link return_group_member/2}.</dd>
  86. %% <dt>`cull_interval'</dt>
  87. %% <dd>Time between checks for stale pool members. Specified as
  88. %% `{Time, Unit}' where `Time' is a non-negative integer and `Unit' is
  89. %% one of `min', `sec', `ms', or `mu'. The default value of `{1, min}'
  90. %% triggers a once per minute check to remove members that have not
  91. %% been accessed in `max_age' time units. Culling can be disabled by
  92. %% specifying a zero time vaule (e.g. `{0, min}'. Culling will also be
  93. %% disabled if `init_count' is the same as `max_count'.</dd>
  94. %% <dt>`max_age'</dt>
  95. %% <dd>Members idle longer than `max_age' time units are removed from
  96. %% the pool when stale checking is enabled via
  97. %% `cull_interval'. Culling of idle members will never reduce the pool
  98. %% below `init_count'. The value is specified as `{Time, Unit}'. Note
  99. %% that timers are not set on individual pool members and may remain
  100. %% in the pool beyond the configured `max_age' value since members are
  101. %% only removed on the interval configured via `cull_interval'. The
  102. %% default value is `{30, sec}'.</dd>
  103. %% <dt>`member_start_timeout'</dt>
  104. %% <dd>Time limit for member starts. Specified as `{Time,
  105. %% Unit}'. Defaults to `{1, min}'.</dd>
  106. %% </dl>
  107. new_pool(PoolConfig) ->
  108. pooler_sup:new_pool(PoolConfig).
  109. %% @doc Terminate the named pool.
  110. rm_pool(PoolName) ->
  111. pooler_sup:rm_pool(PoolName).
  112. %% @doc Terminates the group and all pools in that group.
  113. %%
  114. %% If termination of any member pool fails, `rm_group/1` returns
  115. %% `{error, {failed_delete_pools, Pools}}`, where `Pools` is a list
  116. %% of pools that failed to terminate.
  117. %%
  118. %% The group is NOT terminated if any member pool did not
  119. %% successfully terminate.
  120. %%
  121. -spec rm_group(atom()) -> ok | {error, {failed_rm_pools, [atom()]}}.
  122. rm_group(GroupName) ->
  123. case pg2:get_local_members(GroupName) of
  124. {error, {no_such_group, GroupName}} ->
  125. ok;
  126. Pools ->
  127. case rm_group_members(Pools) of
  128. [] ->
  129. pg2:delete(GroupName);
  130. Failures ->
  131. {error, {failed_rm_pools, Failures}}
  132. end
  133. end.
  134. -spec rm_group_members([pid()]) -> [atom()].
  135. rm_group_members(MemberPids) ->
  136. lists:foldl(
  137. fun(MemberPid, Acc) ->
  138. Pool = gen_server:call(MemberPid, dump_pool),
  139. PoolName = Pool#pool.name,
  140. case pooler_sup:rm_pool(PoolName) of
  141. ok -> Acc;
  142. _ -> [PoolName | Acc]
  143. end
  144. end,
  145. [],
  146. MemberPids).
  147. %% @doc Get child spec described by the proplist `PoolConfig'.
  148. %%
  149. %% See {@link pooler:new_pool/1} for info about `PoolConfig'.
  150. -spec pool_child_spec([{atom(), term()}]) -> supervisor:child_spec().
  151. pool_child_spec(PoolConfig) ->
  152. pooler_sup:pool_child_spec(PoolConfig).
  153. %% @doc For INTERNAL use. Adds `MemberPid' to the pool.
  154. -spec accept_member(atom() | pid(), pid() | {noproc, _}) -> ok.
  155. accept_member(PoolName, MemberPid) ->
  156. gen_server:call(PoolName, {accept_member, MemberPid}).
  157. %% @doc Obtain exclusive access to a member from `PoolName'.
  158. %%
  159. %% If no free members are available, 'error_no_members' is returned.
  160. %%
  161. -spec take_member(atom() | pid()) -> pid() | error_no_members.
  162. take_member(PoolName) when is_atom(PoolName) orelse is_pid(PoolName) ->
  163. gen_server:call(PoolName, {take_member, 0}, infinity).
  164. %% @doc Obtain exclusive access to a member of 'PoolName'.
  165. %%
  166. %% If no members are available, wait for up to Timeout milliseconds for a member
  167. %% to become available. Waiting requests are served in FIFO order. If no member
  168. %% is available within the specified timeout, error_no_members is returned.
  169. %% `Timeout' can be either milliseconds as integer or `{duration, time_unit}'
  170. %%
  171. -spec take_member(atom() | pid(), non_neg_integer() | time_spec()) -> pid() | error_no_members.
  172. take_member(PoolName, Timeout) when is_atom(PoolName) orelse is_pid(PoolName) ->
  173. gen_server:call(PoolName, {take_member, time_as_millis(Timeout)}, infinity).
  174. %% @doc Take a member from a randomly selected member of the group
  175. %% `GroupName'. Returns `MemberPid' or `error_no_members'. If no
  176. %% members are available in the randomly chosen pool, all other pools
  177. %% in the group are tried in order.
  178. -spec take_group_member(atom()) -> pid() | error_no_members | {error_no_group, atom()}.
  179. take_group_member(GroupName) ->
  180. case pg2:get_local_members(GroupName) of
  181. {error, {no_such_group, GroupName}} ->
  182. {error_no_group, GroupName};
  183. [] ->
  184. error_no_members;
  185. Pools ->
  186. %% Put a random member at the front of the list and then
  187. %% return the first member you can walking the list.
  188. {_, _, X} = os:timestamp(),
  189. Idx = (X rem length(Pools)) + 1,
  190. {PoolPid, Rest} = extract_nth(Idx, Pools),
  191. take_first_pool([PoolPid | Rest])
  192. end.
  193. take_first_pool([PoolPid | Rest]) ->
  194. case take_member(PoolPid) of
  195. error_no_members ->
  196. take_first_pool(Rest);
  197. Member ->
  198. ets:insert(?POOLER_GROUP_TABLE, {Member, PoolPid}),
  199. Member
  200. end;
  201. take_first_pool([]) ->
  202. error_no_members.
  203. %% this helper function returns `{Nth_Elt, Rest}' where `Nth_Elt' is
  204. %% the nth element of `L' and `Rest' is `L -- [Nth_Elt]'.
  205. extract_nth(N, L) ->
  206. extract_nth(N, L, []).
  207. extract_nth(1, [H | T], Acc) ->
  208. {H, Acc ++ T};
  209. extract_nth(N, [H | T], Acc) ->
  210. extract_nth(N - 1, T, [H | Acc]);
  211. extract_nth(_, [], _) ->
  212. error(badarg).
  213. %% @doc Return a member that was taken from the group
  214. %% `GroupName'. This is a convenience function for
  215. %% `return_group_member/3' with `Status' of `ok'.
  216. -spec return_group_member(atom(), pid() | error_no_members) -> ok.
  217. return_group_member(GroupName, MemberPid) ->
  218. return_group_member(GroupName, MemberPid, ok).
  219. %% @doc Return a member that was taken from the group `GroupName'. If
  220. %% `Status' is `ok' the member is returned to the pool from which is
  221. %% came. If `Status' is `fail' the member will be terminated and a new
  222. %% member added to the appropriate pool.
  223. -spec return_group_member(atom(), pid() | error_no_members, ok | fail) -> ok.
  224. return_group_member(_, error_no_members, _) ->
  225. ok;
  226. return_group_member(_GroupName, MemberPid, Status) ->
  227. case ets:lookup(?POOLER_GROUP_TABLE, MemberPid) of
  228. [{MemberPid, PoolPid}] ->
  229. return_member(PoolPid, MemberPid, Status);
  230. [] ->
  231. ok
  232. end.
  233. %% @doc Return a member to the pool so it can be reused.
  234. %%
  235. %% If `Status' is 'ok', the member is returned to the pool. If
  236. %% `Status' is 'fail', the member is destroyed and a new member is
  237. %% added to the pool in its place.
  238. -spec return_member(atom() | pid(), pid() | error_no_members, ok | fail) -> ok.
  239. return_member(PoolName, Pid, Status) when is_pid(Pid) andalso
  240. (is_atom(PoolName) orelse
  241. is_pid(PoolName)) andalso
  242. (Status =:= ok orelse
  243. Status =:= fail) ->
  244. gen_server:call(PoolName, {return_member, Pid, Status}, infinity),
  245. ok;
  246. return_member(_, error_no_members, _) ->
  247. ok.
  248. %% @doc Return a member to the pool so it can be reused.
  249. %%
  250. -spec return_member(atom() | pid(), pid() | error_no_members) -> ok.
  251. return_member(PoolName, Pid) when is_pid(Pid) andalso
  252. (is_atom(PoolName) orelse is_pid(PoolName)) ->
  253. gen_server:call(PoolName, {return_member, Pid, ok}, infinity),
  254. ok;
  255. return_member(_, error_no_members) ->
  256. ok.
  257. %% @doc Obtain runtime state info for all pools.
  258. %%
  259. %% Format of the return value is subject to change.
  260. -spec pool_stats(atom() | pid()) -> [tuple()].
  261. pool_stats(PoolName) ->
  262. gen_server:call(PoolName, pool_stats).
  263. %% ------------------------------------------------------------------
  264. %% gen_server Function Definitions
  265. %% ------------------------------------------------------------------
  266. -spec init(#pool{}) -> {'ok', #pool{}, 0}.
  267. init(#pool{}=Pool) ->
  268. #pool{init_count = N} = Pool,
  269. MemberSup = pooler_pool_sup:member_sup_name(Pool),
  270. Pool1 = set_member_sup(Pool, MemberSup),
  271. %% This schedules the next cull when the pool is configured for
  272. %% such and is otherwise a no-op.
  273. Pool2 = cull_members_from_pool(Pool1),
  274. {ok, NewPool} = init_members_sync(N, Pool2),
  275. %% trigger an immediate timeout, handled by handle_info to allow
  276. %% us to register with pg2. We use the timeout mechanism to ensure
  277. %% that a server is added to a group only when it is ready to
  278. %% process messages.
  279. {ok, NewPool, 0}.
  280. set_member_sup(#pool{} = Pool, MemberSup) ->
  281. Pool#pool{member_sup = MemberSup}.
  282. handle_call({take_member, Timeout}, From = {APid, _}, #pool{} = Pool) when is_pid(APid) ->
  283. maybe_reply(take_member_from_pool_queued(Pool, From, Timeout));
  284. handle_call({return_member, Pid, Status}, {_CPid, _Tag}, Pool) ->
  285. {reply, ok, do_return_member(Pid, Status, Pool)};
  286. handle_call({accept_member, Pid}, _From, Pool) ->
  287. {reply, ok, do_accept_member(Pid, Pool)};
  288. handle_call(stop, _From, Pool) ->
  289. {stop, normal, stop_ok, Pool};
  290. handle_call(pool_stats, _From, Pool) ->
  291. {reply, dict:to_list(Pool#pool.all_members), Pool};
  292. handle_call(dump_pool, _From, Pool) ->
  293. {reply, Pool, Pool};
  294. handle_call(_Request, _From, Pool) ->
  295. {noreply, Pool}.
  296. -spec handle_cast(_,_) -> {'noreply', _}.
  297. handle_cast(_Msg, Pool) ->
  298. {noreply, Pool}.
  299. -spec handle_info(_, _) -> {'noreply', _}.
  300. handle_info({requestor_timeout, From}, Pool = #pool{ queued_requestors = RequestorQueue }) ->
  301. NewQueue = queue:filter(fun({RequestorFrom, _TRef}) when RequestorFrom =:= From ->
  302. gen_server:reply(RequestorFrom, error_no_members),
  303. false;
  304. ({_, _}) ->
  305. true
  306. end, RequestorQueue),
  307. {noreply, Pool#pool{ queued_requestors = NewQueue} };
  308. handle_info(timeout, #pool{group = undefined} = Pool) ->
  309. %% ignore
  310. {noreply, Pool};
  311. handle_info(timeout, #pool{group = Group} = Pool) ->
  312. ok = pg2:create(Group),
  313. ok = pg2:join(Group, self()),
  314. {noreply, Pool};
  315. handle_info({'DOWN', MRef, process, Pid, Reason}, State) ->
  316. State1 =
  317. case dict:find(Pid, State#pool.all_members) of
  318. {ok, {_PoolName, _ConsumerPid, _Time}} ->
  319. do_return_member(Pid, fail, State);
  320. error ->
  321. case dict:find(Pid, State#pool.consumer_to_pid) of
  322. {ok, {MRef, Pids}} ->
  323. IsOk = case Reason of
  324. normal -> ok;
  325. _Crash -> fail
  326. end,
  327. lists:foldl(
  328. fun(P, S) -> do_return_member(P, IsOk, S) end,
  329. State, Pids);
  330. error ->
  331. State
  332. end
  333. end,
  334. {noreply, State1};
  335. handle_info(cull_pool, Pool) ->
  336. {noreply, cull_members_from_pool(Pool)};
  337. handle_info(_Info, State) ->
  338. {noreply, State}.
  339. -spec terminate(_, _) -> 'ok'.
  340. terminate(_Reason, _State) ->
  341. ok.
  342. -spec code_change(_, _, _) -> {'ok', _}.
  343. code_change(_OldVsn, State, _Extra) ->
  344. {ok, State}.
  345. %% ------------------------------------------------------------------
  346. %% Internal Function Definitions
  347. %% ------------------------------------------------------------------
  348. do_accept_member({StarterPid, Pid},
  349. #pool{
  350. all_members = AllMembers,
  351. starting_members = StartingMembers0,
  352. member_start_timeout = StartTimeout
  353. } = Pool) when is_pid(Pid) ->
  354. %% make sure we don't accept a timedout member
  355. Pool1 = #pool{starting_members = StartingMembers} =
  356. remove_stale_starting_members(Pool, StartingMembers0, StartTimeout),
  357. case lists:keymember(StarterPid, 1, StartingMembers) of
  358. false ->
  359. %% A starter completed even though we invalidated the pid
  360. %% Ask the starter to kill the child and stop. In most cases, the
  361. %% starter has already received this message. However, when pools
  362. %% are dynamically re-created with the same name, it is possible
  363. %% to receive an accept from a pool that has since gone away.
  364. %% In this case, we should cleanup.
  365. pooler_starter:stop_member_async(StarterPid),
  366. Pool1;
  367. true ->
  368. StartingMembers1 = lists:keydelete(StarterPid, 1, StartingMembers),
  369. MRef = erlang:monitor(process, Pid),
  370. Entry = {MRef, free, os:timestamp()},
  371. AllMembers1 = store_all_members(Pid, Entry, AllMembers),
  372. pooler_starter:stop(StarterPid),
  373. maybe_reply_with_pid(Pid, Pool1#pool{all_members = AllMembers1,
  374. starting_members = StartingMembers1})
  375. end;
  376. do_accept_member({StarterPid, _Reason},
  377. #pool{starting_members = StartingMembers0,
  378. member_start_timeout = StartTimeout} = Pool) ->
  379. %% member start failed, remove in-flight ref and carry on.
  380. pooler_starter:stop(StarterPid),
  381. Pool1 = #pool{starting_members = StartingMembers} =
  382. remove_stale_starting_members(Pool, StartingMembers0,
  383. StartTimeout),
  384. StartingMembers1 = lists:keydelete(StarterPid, 1, StartingMembers),
  385. Pool1#pool{starting_members = StartingMembers1}.
  386. maybe_reply_with_pid(Pid,
  387. Pool = #pool{queued_requestors = QueuedRequestors,
  388. free_pids = Free,
  389. free_count = NumFree}) when is_pid(Pid) ->
  390. case queue:out(QueuedRequestors) of
  391. {empty, _} ->
  392. Pool#pool{free_pids = [Pid | Free],
  393. free_count = NumFree + 1};
  394. {{value, {From = {APid, _}, TRef}}, NewQueuedRequestors} when is_pid(APid) ->
  395. reply_to_queued_requestor(TRef, Pid, From, NewQueuedRequestors, Pool)
  396. end.
  397. reply_to_queued_requestor(TRef, Pid, From = {APid, _}, NewQueuedRequestors, Pool) when is_pid(APid) ->
  398. erlang:cancel_timer(TRef),
  399. Pool1 = take_member_bookkeeping(Pid, From, NewQueuedRequestors, Pool),
  400. send_metric(Pool, in_use_count, Pool1#pool.in_use_count, histogram),
  401. send_metric(Pool, free_count, Pool1#pool.free_count, histogram),
  402. send_metric(Pool, events, error_no_members, history),
  403. gen_server:reply(From, Pid),
  404. Pool1.
  405. -spec take_member_bookkeeping(pid(),
  406. {pid(), _},
  407. [pid()] | p_requestor_queue(),
  408. #pool{}) -> #pool{}.
  409. take_member_bookkeeping(MemberPid,
  410. {CPid, _},
  411. Rest,
  412. Pool = #pool{in_use_count = NumInUse,
  413. free_count = NumFree,
  414. consumer_to_pid = CPMap,
  415. all_members = AllMembers})
  416. when is_pid(MemberPid),
  417. is_pid(CPid),
  418. is_list(Rest) ->
  419. Pool#pool{free_pids = Rest,
  420. in_use_count = NumInUse + 1,
  421. free_count = NumFree - 1,
  422. consumer_to_pid = add_member_to_consumer(MemberPid, CPid, CPMap),
  423. all_members = set_cpid_for_member(MemberPid, CPid, AllMembers)
  424. };
  425. take_member_bookkeeping(MemberPid,
  426. {ReplyPid, _Tag},
  427. NewQueuedRequestors,
  428. Pool = #pool{
  429. in_use_count = NumInUse,
  430. all_members = AllMembers,
  431. consumer_to_pid = CPMap
  432. }) ->
  433. Pool#pool{
  434. in_use_count = NumInUse + 1,
  435. all_members = set_cpid_for_member(MemberPid, ReplyPid, AllMembers),
  436. consumer_to_pid = add_member_to_consumer(MemberPid, ReplyPid, CPMap),
  437. queued_requestors = NewQueuedRequestors
  438. }.
  439. -spec remove_stale_starting_members(#pool{}, [{reference(), erlang:timestamp()}],
  440. time_spec()) -> #pool{}.
  441. remove_stale_starting_members(Pool, StartingMembers, MaxAge) ->
  442. Now = os:timestamp(),
  443. MaxAgeSecs = time_as_secs(MaxAge),
  444. FilteredStartingMembers = lists:foldl(fun(SM, AccIn) ->
  445. accumulate_starting_member_not_stale(Pool, Now, SM, MaxAgeSecs, AccIn)
  446. end, [], StartingMembers),
  447. Pool#pool{starting_members = FilteredStartingMembers}.
  448. accumulate_starting_member_not_stale(Pool, Now, SM = {Pid, StartTime}, MaxAgeSecs, AccIn) ->
  449. case secs_between(StartTime, Now) < MaxAgeSecs of
  450. true ->
  451. [SM | AccIn];
  452. false ->
  453. error_logger:error_msg("pool '~s': starting member timeout", [Pool#pool.name]),
  454. send_metric(Pool, starting_member_timeout, {inc, 1}, counter),
  455. pooler_starter:stop_member_async(Pid),
  456. AccIn
  457. end.
  458. init_members_sync(N, #pool{name = PoolName} = Pool) ->
  459. Self = self(),
  460. StartTime = os:timestamp(),
  461. StartRefs = [ {pooler_starter:start_member(Pool, Self), StartTime}
  462. || _I <- lists:seq(1, N) ],
  463. Pool1 = Pool#pool{starting_members = StartRefs},
  464. case collect_init_members(Pool1) of
  465. timeout ->
  466. error_logger:error_msg("pool '~s': exceeded timeout waiting for ~B members",
  467. [PoolName, Pool1#pool.init_count]),
  468. error({timeout, "unable to start members"});
  469. #pool{} = Pool2 ->
  470. {ok, Pool2}
  471. end.
  472. collect_init_members(#pool{starting_members = []} = Pool) ->
  473. Pool;
  474. collect_init_members(#pool{member_start_timeout = StartTimeout} = Pool) ->
  475. Timeout = time_as_millis(StartTimeout),
  476. receive
  477. {accept_member, {Ref, Member}} ->
  478. collect_init_members(do_accept_member({Ref, Member}, Pool))
  479. after
  480. Timeout ->
  481. timeout
  482. end.
  483. -spec take_member_from_pool(#pool{}, {pid(), term()}) ->
  484. {error_no_members | pid(), #pool{}}.
  485. take_member_from_pool(#pool{init_count = InitCount,
  486. max_count = Max,
  487. free_pids = Free,
  488. in_use_count = NumInUse,
  489. free_count = NumFree,
  490. starting_members = StartingMembers,
  491. member_start_timeout = StartTimeout} = Pool,
  492. From) ->
  493. send_metric(Pool, take_rate, 1, meter),
  494. Pool1 = remove_stale_starting_members(Pool, StartingMembers, StartTimeout),
  495. NonStaleStartingMemberCount = length(Pool1#pool.starting_members),
  496. NumCanAdd = Max - (NumInUse + NumFree + NonStaleStartingMemberCount),
  497. case Free of
  498. [] when NumCanAdd =< 0 ->
  499. send_metric(Pool, error_no_members_count, {inc, 1}, counter),
  500. send_metric(Pool, events, error_no_members, history),
  501. {error_no_members, Pool1};
  502. [] when NumCanAdd > 0 ->
  503. %% Limit concurrently starting members to init_count. Add
  504. %% up to init_count members. Starting members here means
  505. %% we always return an error_no_members for a take request
  506. %% when all members are in-use. By adding a batch of new
  507. %% members, the pool should reach a steady state with
  508. %% unused members culled over time (if scheduled cull is
  509. %% enabled).
  510. NumToAdd = max(min(InitCount - NonStaleStartingMemberCount, NumCanAdd), 1),
  511. Pool2 = add_members_async(NumToAdd, Pool1),
  512. send_metric(Pool, error_no_members_count, {inc, 1}, counter),
  513. send_metric(Pool, events, error_no_members, history),
  514. {error_no_members, Pool2};
  515. [Pid|Rest] ->
  516. Pool2 = take_member_bookkeeping(Pid, From, Rest, Pool1),
  517. Pool3 = case Pool2#pool.auto_grow_threshold of
  518. N when is_integer(N) andalso
  519. Pool2#pool.free_count =< N andalso
  520. NumCanAdd > 0 ->
  521. NumToAdd = max(min(InitCount - NonStaleStartingMemberCount, NumCanAdd), 0),
  522. add_members_async(NumToAdd, Pool2);
  523. _ ->
  524. Pool2
  525. end,
  526. send_metric(Pool, in_use_count, Pool3#pool.in_use_count, histogram),
  527. send_metric(Pool, free_count, Pool3#pool.free_count, histogram),
  528. {Pid, Pool3}
  529. end.
  530. -spec take_member_from_pool_queued(#pool{},
  531. {pid(), _},
  532. non_neg_integer()) ->
  533. {error_no_members | queued | pid(), #pool{}}.
  534. take_member_from_pool_queued(Pool0 = #pool{queue_max = QMax,
  535. queued_requestors = Requestors},
  536. From = {CPid, _},
  537. Timeout) when is_pid(CPid) ->
  538. case {take_member_from_pool(Pool0, From), queue:len(Requestors)} of
  539. {{error_no_members, Pool1}, QLen} when QLen >= QMax ->
  540. send_metric(Pool1, events, error_no_members, history),
  541. send_metric(Pool1, queue_max_reached, {inc, 1}, counter),
  542. {error_no_members, Pool1};
  543. {{error_no_members, Pool1}, _} when Timeout =:= 0 ->
  544. {error_no_members, Pool1};
  545. {{error_no_members, Pool1 = #pool{queued_requestors = QueuedRequestors}}, QueueCount} ->
  546. TRef = erlang:send_after(Timeout, self(), {requestor_timeout, From}),
  547. send_metric(Pool1, queue_count, QueueCount, histogram),
  548. {queued, Pool1#pool{queued_requestors = queue:in({From, TRef}, QueuedRequestors)}};
  549. {{Member, NewPool}, _} when is_pid(Member) ->
  550. {Member, NewPool}
  551. end.
  552. %% @doc Add `Count' members to `Pool' asynchronously. Returns updated
  553. %% `Pool' record with starting member refs added to field
  554. %% `starting_members'.
  555. add_members_async(Count, #pool{starting_members = StartingMembers} = Pool) ->
  556. StartTime = os:timestamp(),
  557. StartRefs = [ {pooler_starter:start_member(Pool), StartTime}
  558. || _I <- lists:seq(1, Count) ],
  559. Pool#pool{starting_members = StartRefs ++ StartingMembers}.
  560. -spec do_return_member(pid(), ok | fail, #pool{}) -> #pool{}.
  561. do_return_member(Pid, ok, #pool{name = PoolName,
  562. all_members = AllMembers,
  563. queued_requestors = QueuedRequestors} = Pool) ->
  564. clean_group_table(Pid, Pool),
  565. case dict:find(Pid, AllMembers) of
  566. {ok, {_, free, _}} ->
  567. Fmt = "pool '~s': ignored return of free member ~p",
  568. error_logger:warning_msg(Fmt, [PoolName, Pid]),
  569. Pool;
  570. {ok, {MRef, CPid, _}} ->
  571. #pool{free_pids = Free, in_use_count = NumInUse,
  572. free_count = NumFree} = Pool,
  573. Pool1 = Pool#pool{in_use_count = NumInUse - 1},
  574. Entry = {MRef, free, os:timestamp()},
  575. Pool2 = Pool1#pool{all_members = store_all_members(Pid, Entry, AllMembers),
  576. consumer_to_pid = cpmap_remove(Pid, CPid,
  577. Pool1#pool.consumer_to_pid)},
  578. case queue:out(QueuedRequestors) of
  579. {empty, _ } ->
  580. Pool2#pool{free_pids = [Pid | Free], free_count = NumFree + 1};
  581. {{value, {From = {APid, _}, TRef}}, NewQueuedRequestors} when is_pid(APid) ->
  582. reply_to_queued_requestor(TRef, Pid, From, NewQueuedRequestors, Pool2)
  583. end;
  584. error ->
  585. Pool
  586. end;
  587. do_return_member(Pid, fail, #pool{all_members = AllMembers} = Pool) ->
  588. % for the fail case, perhaps the member crashed and was alerady
  589. % removed, so use find instead of fetch and ignore missing.
  590. clean_group_table(Pid, Pool),
  591. case dict:find(Pid, AllMembers) of
  592. {ok, {_MRef, _, _}} ->
  593. Pool1 = remove_pid(Pid, Pool),
  594. add_members_async(1, Pool1);
  595. error ->
  596. Pool
  597. end.
  598. clean_group_table(_MemberPid, #pool{group = undefined}) ->
  599. ok;
  600. clean_group_table(MemberPid, #pool{group = _GroupName}) ->
  601. ets:delete(?POOLER_GROUP_TABLE, MemberPid).
  602. % @doc Remove `Pid' from the pid list associated with `CPid' in the
  603. % consumer to member map given by `CPMap'.
  604. %
  605. % If `Pid' is the last element in `CPid's pid list, then the `CPid'
  606. % entry is removed entirely.
  607. %
  608. -spec cpmap_remove(pid(), pid() | free, p_dict()) -> p_dict().
  609. cpmap_remove(_Pid, free, CPMap) ->
  610. CPMap;
  611. cpmap_remove(Pid, CPid, CPMap) ->
  612. case dict:find(CPid, CPMap) of
  613. {ok, {MRef, Pids0}} ->
  614. Pids1 = lists:delete(Pid, Pids0),
  615. case Pids1 of
  616. [_H|_T] ->
  617. dict:store(CPid, {MRef, Pids1}, CPMap);
  618. [] ->
  619. %% no more members for this consumer
  620. erlang:demonitor(MRef, [flush]),
  621. dict:erase(CPid, CPMap)
  622. end;
  623. error ->
  624. % FIXME: this shouldn't happen, should we log or error?
  625. CPMap
  626. end.
  627. % @doc Remove and kill a pool member.
  628. %
  629. % Handles in-use and free members. Logs an error if the pid is not
  630. % tracked in state.all_members.
  631. %
  632. -spec remove_pid(pid(), #pool{}) -> #pool{}.
  633. remove_pid(Pid, Pool) ->
  634. #pool{name = PoolName,
  635. all_members = AllMembers,
  636. consumer_to_pid = CPMap,
  637. stop_mfa = StopMFA} = Pool,
  638. case dict:find(Pid, AllMembers) of
  639. {ok, {MRef, free, _Time}} ->
  640. % remove an unused member
  641. erlang:demonitor(MRef, [flush]),
  642. FreePids = lists:delete(Pid, Pool#pool.free_pids),
  643. NumFree = Pool#pool.free_count - 1,
  644. Pool1 = Pool#pool{free_pids = FreePids, free_count = NumFree},
  645. terminate_pid(Pid, StopMFA),
  646. send_metric(Pool1, killed_free_count, {inc, 1}, counter),
  647. Pool1#pool{all_members = dict:erase(Pid, AllMembers)};
  648. {ok, {MRef, CPid, _Time}} ->
  649. %% remove a member being consumed. No notice is sent to
  650. %% the consumer.
  651. erlang:demonitor(MRef, [flush]),
  652. Pool1 = Pool#pool{in_use_count = Pool#pool.in_use_count - 1},
  653. terminate_pid(Pid, StopMFA),
  654. send_metric(Pool1, killed_in_use_count, {inc, 1}, counter),
  655. Pool1#pool{consumer_to_pid = cpmap_remove(Pid, CPid, CPMap),
  656. all_members = dict:erase(Pid, AllMembers)};
  657. error ->
  658. error_logger:error_report({{pool, PoolName}, unknown_pid, Pid,
  659. erlang:get_stacktrace()}),
  660. send_metric(Pool, events, unknown_pid, history),
  661. Pool
  662. end.
  663. -spec store_all_members(pid(),
  664. {reference(), free | pid(), {_, _, _}}, p_dict()) -> p_dict().
  665. store_all_members(Pid, Val = {_MRef, _CPid, _Time}, AllMembers) ->
  666. dict:store(Pid, Val, AllMembers).
  667. -spec set_cpid_for_member(pid(), pid(), p_dict()) -> p_dict().
  668. set_cpid_for_member(MemberPid, CPid, AllMembers) ->
  669. dict:update(MemberPid,
  670. fun({MRef, free, Time = {_, _, _}}) ->
  671. {MRef, CPid, Time}
  672. end, AllMembers).
  673. -spec add_member_to_consumer(pid(), pid(), p_dict()) -> p_dict().
  674. add_member_to_consumer(MemberPid, CPid, CPMap) ->
  675. %% we can't use dict:update here because we need to create the
  676. %% monitor if we aren't already tracking this consumer.
  677. case dict:find(CPid, CPMap) of
  678. {ok, {MRef, MList}} ->
  679. dict:store(CPid, {MRef, [MemberPid | MList]}, CPMap);
  680. error ->
  681. MRef = erlang:monitor(process, CPid),
  682. dict:store(CPid, {MRef, [MemberPid]}, CPMap)
  683. end.
  684. -spec cull_members_from_pool(#pool{}) -> #pool{}.
  685. cull_members_from_pool(#pool{cull_interval = {0, _}} = Pool) ->
  686. %% 0 cull_interval means do not cull
  687. Pool;
  688. cull_members_from_pool(#pool{init_count = C, max_count = C} = Pool) ->
  689. %% if init_count matches max_count, then we will not dynamically
  690. %% add capacity and should not schedule culling regardless of
  691. %% cull_interval config.
  692. Pool;
  693. cull_members_from_pool(#pool{name = PoolName,
  694. free_count = FreeCount,
  695. init_count = InitCount,
  696. in_use_count = InUseCount,
  697. cull_interval = Delay,
  698. max_age = MaxAge,
  699. all_members = AllMembers} = Pool) ->
  700. MaxCull = FreeCount - (InitCount - InUseCount),
  701. Pool1 = case MaxCull > 0 of
  702. true ->
  703. MemberInfo = member_info(Pool#pool.free_pids, AllMembers),
  704. ExpiredMembers =
  705. expired_free_members(MemberInfo, os:timestamp(), MaxAge),
  706. CullList = lists:sublist(ExpiredMembers, MaxCull),
  707. lists:foldl(fun({CullMe, _}, S) -> remove_pid(CullMe, S) end,
  708. Pool, CullList);
  709. false ->
  710. Pool
  711. end,
  712. schedule_cull(PoolName, Delay),
  713. Pool1.
  714. -spec schedule_cull(PoolName :: atom() | pid(),
  715. Delay :: time_spec()) -> reference().
  716. %% @doc Schedule a pool cleaning or "cull" for `PoolName' in which
  717. %% members older than `max_age' will be removed until the pool has
  718. %% `init_count' members. Uses `erlang:send_after/3' for light-weight
  719. %% timer that will be auto-cancelled upon pooler shutdown.
  720. schedule_cull(PoolName, Delay) ->
  721. DelayMillis = time_as_millis(Delay),
  722. %% use pid instead of server name atom to take advantage of
  723. %% automatic cancelling
  724. erlang:send_after(DelayMillis, PoolName, cull_pool).
  725. -spec member_info([pid()], p_dict()) -> [{pid(), member_info()}].
  726. member_info(Pids, AllMembers) ->
  727. [ {P, dict:fetch(P, AllMembers)} || P <- Pids ].
  728. -spec expired_free_members(Members :: [{pid(), member_info()}],
  729. Now :: {_, _, _},
  730. MaxAge :: time_spec()) -> [{pid(), free_member_info()}].
  731. expired_free_members(Members, Now, MaxAge) ->
  732. MaxMicros = time_as_micros(MaxAge),
  733. [ MI || MI = {_, {_, free, LastReturn}} <- Members,
  734. timer:now_diff(Now, LastReturn) >= MaxMicros ].
  735. %% Send a metric using the metrics module from application config or
  736. %% do nothing.
  737. -spec send_metric(Pool :: #pool{},
  738. Label :: atom(),
  739. Value :: metric_value(),
  740. Type :: metric_type()) -> ok.
  741. send_metric(#pool{metrics_mod = pooler_no_metrics}, _Label, _Value, _Type) ->
  742. ok;
  743. send_metric(#pool{name = PoolName, metrics_mod = MetricsMod,
  744. metrics_api = exometer}, Label, {inc, Value}, counter) ->
  745. MetricName = pool_metric_exometer(PoolName, Label),
  746. MetricsMod:update_or_create(MetricName, Value, counter, []),
  747. ok;
  748. send_metric(#pool{name = PoolName, metrics_mod = MetricsMod,
  749. metrics_api = exometer}, Label, {dec, Value}, counter) ->
  750. MetricName = pool_metric_exometer(PoolName, Label),
  751. MetricsMod:update_or_create(MetricName, - Value, counter, []),
  752. ok;
  753. % Exometer does not support 'history' type metrics right now.
  754. send_metric(#pool{name = _PoolName, metrics_mod = _MetricsMod,
  755. metrics_api = exometer}, _Label, _Value, history) ->
  756. ok;
  757. send_metric(#pool{name = PoolName, metrics_mod = MetricsMod,
  758. metrics_api = exometer}, Label, Value, Type) ->
  759. MetricName = pool_metric_exometer(PoolName, Label),
  760. MetricsMod:update_or_create(MetricName, Value, Type, []),
  761. ok;
  762. %folsom API is the default one.
  763. send_metric(#pool{name = PoolName, metrics_mod = MetricsMod, metrics_api = folsom},
  764. Label, Value, Type) ->
  765. MetricName = pool_metric(PoolName, Label),
  766. MetricsMod:notify(MetricName, Value, Type),
  767. ok.
  768. -spec pool_metric(atom(), atom()) -> binary().
  769. pool_metric(PoolName, Metric) ->
  770. iolist_to_binary([<<"pooler.">>, atom_to_binary(PoolName, utf8),
  771. ".", atom_to_binary(Metric, utf8)]).
  772. %% Exometer metric names are lists, not binaries.
  773. -spec pool_metric_exometer(atom(), atom()) -> nonempty_list(binary()).
  774. pool_metric_exometer(PoolName, Metric) ->
  775. [<<"pooler">>, atom_to_binary(PoolName, utf8),
  776. atom_to_binary(Metric, utf8)].
  777. -spec time_as_secs(time_spec()) -> non_neg_integer().
  778. time_as_secs({Time, Unit}) ->
  779. time_as_micros({Time, Unit}) div 1000000.
  780. -spec time_as_millis(time_spec()) -> non_neg_integer().
  781. %% @doc Convert time unit into milliseconds.
  782. time_as_millis({Time, Unit}) ->
  783. time_as_micros({Time, Unit}) div 1000;
  784. %% Allows blind convert
  785. time_as_millis(Time) when is_integer(Time) ->
  786. Time.
  787. -spec time_as_micros(time_spec()) -> non_neg_integer().
  788. %% @doc Convert time unit into microseconds
  789. time_as_micros({Time, min}) ->
  790. 60 * 1000 * 1000 * Time;
  791. time_as_micros({Time, sec}) ->
  792. 1000 * 1000 * Time;
  793. time_as_micros({Time, ms}) ->
  794. 1000 * Time;
  795. time_as_micros({Time, mu}) ->
  796. Time.
  797. secs_between({Mega1, Secs1, _}, {Mega2, Secs2, _}) ->
  798. (Mega2 - Mega1) * 1000000 + (Secs2 - Secs1).
  799. -spec maybe_reply({'queued' | 'error_no_members' | pid(), #pool{}}) ->
  800. {noreply, #pool{}} | {reply, 'error_no_members' | pid(), #pool{}}.
  801. maybe_reply({Member, NewPool}) ->
  802. case Member of
  803. queued ->
  804. {noreply, NewPool};
  805. error_no_members ->
  806. {reply, error_no_members, NewPool};
  807. Member when is_pid(Member) ->
  808. {reply, Member, NewPool}
  809. end.
  810. %% Implementation of a best-effort termination for a pool member:
  811. %% Terminates the pid's pool member given a MFA that gets applied. The list
  812. %% of arguments must contain the fixed atom ?POOLER_PID, which is replaced
  813. %% by the target pid. Failure to provide a valid MFA will lead to use the
  814. %% default callback, i.e `erlang:exit(Pid, kill)`.
  815. -spec terminate_pid(pid(), {atom(), atom(), [term()]}) -> ok.
  816. terminate_pid(Pid, {Mod, Fun, Args}) when is_list(Args) ->
  817. NewArgs = [case Arg of
  818. ?POOLER_PID -> Pid;
  819. _ -> Arg
  820. end || Arg <- Args],
  821. case catch erlang:apply(Mod, Fun, NewArgs) of
  822. {'EXIT', _} ->
  823. terminate_pid(Pid, ?DEFAULT_STOP_MFA);
  824. _Result ->
  825. ok
  826. end;
  827. terminate_pid(Pid, _) ->
  828. terminate_pid(Pid, ?DEFAULT_STOP_MFA).