gproc_lib.erl 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. %% ``The contents of this file are subject to the Erlang Public License,
  2. %% Version 1.1, (the "License"); you may not use this file except in
  3. %% compliance with the License. You should have received a copy of the
  4. %% Erlang Public License along with this software. If not, it can be
  5. %% retrieved via the world wide web at http://www.erlang.org/.
  6. %%
  7. %% Software distributed under the License is distributed on an "AS IS"
  8. %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
  9. %% the License for the specific language governing rights and limitations
  10. %% under the License.
  11. %%
  12. %% The Initial Developer of the Original Code is Ericsson Utvecklings AB.
  13. %% Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
  14. %% AB. All Rights Reserved.''
  15. %%
  16. %% @author Ulf Wiger <ulf@wiger.net>
  17. %%
  18. %% @doc Extended process registry
  19. %% <p>This module implements an extended process registry</p>
  20. %% <p>For a detailed description, see gproc/doc/erlang07-wiger.pdf.</p>
  21. %% @end
  22. -module(gproc_lib).
  23. -export([await/3,
  24. do_set_counter_value/3,
  25. do_set_value/3,
  26. ensure_monitor/2,
  27. insert_many/4,
  28. insert_reg/4,
  29. remove_many/4,
  30. remove_reg/3, remove_reg/4,
  31. add_monitor/3,
  32. remove_monitor/3,
  33. remove_monitors/3,
  34. remove_reverse_mapping/3,
  35. notify/2, notify/3,
  36. remove_wait/4,
  37. update_aggr_counter/3,
  38. update_counter/3,
  39. valid_opts/2]).
  40. -include("gproc_int.hrl").
  41. -include("gproc.hrl").
  42. %% We want to store names and aggregated counters with the same
  43. %% structure as properties, but at the same time, we must ensure
  44. %% that the key is unique. We replace the Pid in the key part
  45. %% with an atom. To know which Pid owns the object, we lug the
  46. %% Pid around as payload as well. This is a bit redundant, but
  47. %% symmetric.
  48. %%
  49. -spec insert_reg(key(), any(), pid() | shared, scope()) -> boolean().
  50. insert_reg({T,_,Name} = K, Value, Pid, Scope) when T==a; T==n ->
  51. MaybeScan = fun() ->
  52. if T==a ->
  53. Initial = scan_existing_counters(Scope, Name),
  54. ets:insert(?TAB, {{K,a}, Pid, Initial});
  55. true ->
  56. true
  57. end
  58. end,
  59. Info = [{{K, T}, Pid, Value}, {{Pid,K}, []}],
  60. case ets:insert_new(?TAB, Info) of
  61. true ->
  62. MaybeScan();
  63. false ->
  64. if T==n ->
  65. maybe_waiters(K, Pid, Value, T, Info);
  66. true ->
  67. false
  68. end
  69. end;
  70. insert_reg({c,Scope,Ctr} = Key, Value, Pid, Scope) when Scope==l; Scope==g ->
  71. %% Non-unique keys; store Pid in the key part
  72. K = {Key, Pid},
  73. Kr = {Pid, Key},
  74. Res = ets:insert_new(?TAB, [{K, Pid, Value}, {Kr, [{initial, Value}]}]),
  75. case Res of
  76. true ->
  77. update_aggr_counter(Scope, Ctr, Value);
  78. false ->
  79. ignore
  80. end,
  81. Res;
  82. insert_reg({_,_,_} = Key, Value, Pid, _Scope) when is_pid(Pid) ->
  83. %% Non-unique keys; store Pid in the key part
  84. K = {Key, Pid},
  85. Kr = {Pid, Key},
  86. ets:insert_new(?TAB, [{K, Pid, Value}, {Kr, []}]).
  87. -spec insert_many(type(), scope(), [{key(),any()}], pid()) ->
  88. {true,list()} | false.
  89. insert_many(T, Scope, KVL, Pid) ->
  90. Objs = mk_reg_objs(T, Scope, Pid, KVL),
  91. case ets:insert_new(?TAB, Objs) of
  92. true ->
  93. RevObjs = mk_reg_rev_objs(T, Scope, Pid, KVL),
  94. ets:insert(?TAB, RevObjs),
  95. _ = gproc_lib:ensure_monitor(Pid, Scope),
  96. {true, Objs};
  97. false ->
  98. Existing = [{Obj, ets:lookup(?TAB, K)} || {K,_,_} = Obj <- Objs],
  99. case lists:any(fun({_, [{_, _, _}]}) ->
  100. true;
  101. (_) ->
  102. %% (not found), or waiters registered
  103. false
  104. end, Existing) of
  105. true ->
  106. %% conflict; return 'false', indicating failure
  107. false;
  108. false ->
  109. %% possibly waiters, but they are handled in next step
  110. insert_objects(Existing),
  111. _ = gproc_lib:ensure_monitor(Pid, Scope),
  112. {true, Objs}
  113. end
  114. end.
  115. -spec insert_objects([{key(), pid(), any()}]) -> ok.
  116. insert_objects(Objs) ->
  117. lists:foreach(
  118. fun({{{Id,_} = _K, Pid, V} = Obj, Existing}) ->
  119. ets:insert(?TAB, [Obj, {{Pid, Id}, []}]),
  120. case Existing of
  121. [] -> ok;
  122. [{_, Waiters}] ->
  123. notify_waiters(Waiters, Id, Pid, V)
  124. end
  125. end, Objs).
  126. await({T,C,_} = Key, WPid, {_Pid, Ref} = From) ->
  127. Rev = {{WPid,Key}, []},
  128. case ets:lookup(?TAB, {Key,T}) of
  129. [{_, P, Value}] ->
  130. %% for symmetry, we always reply with Ref and then send a message
  131. if C == g ->
  132. %% in the global case, we bundle the reply, since otherwise
  133. %% the messages can pass each other
  134. {reply, {Ref, {Key, P, Value}}};
  135. true ->
  136. gen_server:reply(From, Ref),
  137. WPid ! {gproc, Ref, registered, {Key, P, Value}},
  138. noreply
  139. end;
  140. [{K, Waiters}] ->
  141. NewWaiters = [{WPid,Ref} | Waiters],
  142. W = {K, NewWaiters},
  143. ets:insert(?TAB, [W, Rev]),
  144. _ = gproc_lib:ensure_monitor(WPid,C),
  145. {reply, Ref, [W,Rev]};
  146. [] ->
  147. W = {{Key,T}, [{WPid,Ref}]},
  148. ets:insert(?TAB, [W, Rev]),
  149. _ = gproc_lib:ensure_monitor(WPid,C),
  150. {reply, Ref, [W,Rev]}
  151. end.
  152. maybe_waiters(K, Pid, Value, T, Info) ->
  153. case ets:lookup(?TAB, {K,T}) of
  154. [{_, Waiters}] when is_list(Waiters) ->
  155. ets:insert(?TAB, Info),
  156. notify_waiters(Waiters, K, Pid, Value),
  157. true;
  158. [_] ->
  159. false
  160. end.
  161. -spec notify_waiters([{pid(), reference()}], key(), pid(), any()) -> ok.
  162. notify_waiters(Waiters, K, Pid, V) ->
  163. _ = [begin
  164. P ! {gproc, Ref, registered, {K, Pid, V}},
  165. case P of
  166. Pid -> ignore;
  167. _ ->
  168. ets:delete(?TAB, {P, K})
  169. end
  170. end || {P, Ref} <- Waiters],
  171. ok.
  172. remove_wait({T,_,_} = Key, Pid, Ref, Waiters) ->
  173. Rev = {Pid,Key},
  174. case remove_from_waiters(Waiters, Pid, Ref) of
  175. [] ->
  176. ets:delete(?TAB, {Key,T}),
  177. ets:delete(?TAB, Rev),
  178. [{delete, [{Key,T}, Rev], []}];
  179. NewWaiters ->
  180. ets:insert(?TAB, {Key, NewWaiters}),
  181. case lists:keymember(Pid, 1, NewWaiters) of
  182. true ->
  183. %% should be extremely unlikely
  184. [{insert, [{Key, NewWaiters}]}];
  185. false ->
  186. %% delete the reverse entry
  187. ets:delete(?TAB, Rev),
  188. [{insert, [{Key, NewWaiters}]},
  189. {delete, [Rev], []}]
  190. end
  191. end.
  192. remove_from_waiters(Waiters, Pid, all) ->
  193. [{P,R} || {P,R} <- Waiters,
  194. P =/= Pid];
  195. remove_from_waiters(Waiters, Pid, Ref) ->
  196. Waiters -- [{Pid, Ref}].
  197. remove_monitors(Key, Pid, MPid) ->
  198. case ets:lookup(?TAB, {Pid, Key}) of
  199. [{_, r}] ->
  200. [];
  201. [{K, Opts}] when is_list(Opts) ->
  202. case lists:keyfind(monitors, 1, Opts) of
  203. false ->
  204. [];
  205. {_, Ms} ->
  206. Ms1 = [{P,R} || {P,R} <- Ms,
  207. P =/= MPid],
  208. NewMs = lists:keyreplace(monitors, 1, Opts, {monitors,Ms1}),
  209. ets:insert(?TAB, {K, NewMs}),
  210. [{insert, [{{Pid,Key}, NewMs}]}]
  211. end;
  212. _ ->
  213. []
  214. end.
  215. mk_reg_objs(T, Scope, Pid, L) when T==n; T==a ->
  216. lists:map(fun({K,V}) ->
  217. {{{T,Scope,K},T}, Pid, V};
  218. (_) ->
  219. erlang:error(badarg)
  220. end, L);
  221. mk_reg_objs(p = T, Scope, Pid, L) ->
  222. lists:map(fun({K,V}) ->
  223. {{{T,Scope,K},Pid}, Pid, V};
  224. (_) ->
  225. erlang:error(badarg)
  226. end, L).
  227. mk_reg_rev_objs(T, Scope, Pid, L) ->
  228. [{{Pid,{T,Scope,K}}, []} || {K,_} <- L].
  229. ensure_monitor(shared, _) ->
  230. ok;
  231. ensure_monitor(Pid, Scope) when Scope==g; Scope==l ->
  232. case ets:insert_new(?TAB, {{Pid, Scope}}) of
  233. false -> ok;
  234. true -> erlang:monitor(process, Pid)
  235. end.
  236. remove_reg(Key, Pid, Event) ->
  237. remove_reg(Key, Pid, Event, []).
  238. remove_reg(Key, Pid, Event, Opts) ->
  239. Reg = remove_reg_1(Key, Pid),
  240. Rev = remove_reverse_mapping(Event, Pid, Key, Opts),
  241. [Reg, Rev].
  242. remove_reverse_mapping(Event, Pid, Key) ->
  243. Opts = case ets:lookup(?TAB, {Pid, Key}) of
  244. [] -> [];
  245. [{_, r}] -> [];
  246. [{_, L}] when is_list(L) ->
  247. L
  248. end,
  249. remove_reverse_mapping(Event, Pid, Key, Opts).
  250. remove_reverse_mapping(Event, Pid, Key, Opts) when Event==unreg;
  251. element(1,Event)==migrated ->
  252. Rev = {Pid, Key},
  253. _ = notify(Event, Key, Opts),
  254. ets:delete(?TAB, Rev),
  255. Rev.
  256. notify(Key, Opts) ->
  257. notify(unreg, Key, Opts).
  258. notify([], _, _) ->
  259. [];
  260. notify(Event, Key, Opts) ->
  261. case lists:keyfind(monitor, 1, Opts) of
  262. false ->
  263. [];
  264. {_, Mons} ->
  265. [begin P ! {gproc, Event, Ref, Key}, P end || {P, Ref} <- Mons,
  266. node(P) == node()]
  267. end.
  268. add_monitor([{monitor, Mons}|T], Pid, Ref) ->
  269. [{monitor, [{Pid,Ref}|Mons]}|T];
  270. add_monitor([H|T], Pid, Ref) ->
  271. [H|add_monitor(T, Pid, Ref)];
  272. add_monitor([], Pid, Ref) ->
  273. [{monitor, [{Pid, Ref}]}].
  274. remove_monitor([{monitor, Mons}|T], Pid, Ref) ->
  275. [{monitor, Mons -- [{Pid, Ref}]}|T];
  276. remove_monitor([H|T], Pid, Ref) ->
  277. [H|remove_monitor(T, Pid, Ref)];
  278. remove_monitor([], _Pid, _Ref) ->
  279. [].
  280. remove_many(T, Scope, L, Pid) ->
  281. lists:flatmap(fun(K) ->
  282. Key = {T, Scope, K},
  283. remove_reg(Key, Pid, unreg, unreg_opts(Key, Pid))
  284. end, L).
  285. unreg_opts(Key, Pid) ->
  286. case ets:lookup(?TAB, {Pid, Key}) of
  287. [] ->
  288. [];
  289. [{_,r}] ->
  290. [];
  291. [{_,Opts}] ->
  292. Opts
  293. end.
  294. remove_reg_1({c,_,_} = Key, Pid) ->
  295. remove_counter_1(Key, ets:lookup_element(?TAB, Reg = {Key,Pid}, 3), Pid),
  296. Reg;
  297. remove_reg_1({a,_,_} = Key, _Pid) ->
  298. ets:delete(?TAB, Reg = {Key,a}),
  299. Reg;
  300. remove_reg_1({n,_,_} = Key, _Pid) ->
  301. ets:delete(?TAB, Reg = {Key,n}),
  302. Reg;
  303. remove_reg_1({_,_,_} = Key, Pid) ->
  304. ets:delete(?TAB, Reg = {Key, Pid}),
  305. Reg.
  306. remove_counter_1({c,C,N} = Key, Val, Pid) ->
  307. Res = ets:delete(?TAB, {Key, Pid}),
  308. update_aggr_counter(C, N, -Val),
  309. Res.
  310. do_set_value({T,_,_} = Key, Value, Pid) ->
  311. K2 = if T==n orelse T==a -> T;
  312. true -> Pid
  313. end,
  314. case (catch ets:lookup_element(?TAB, {Key,K2}, 2)) of
  315. {'EXIT', {badarg, _}} ->
  316. false;
  317. Pid ->
  318. ets:insert(?TAB, {{Key, K2}, Pid, Value});
  319. _ ->
  320. false
  321. end.
  322. do_set_counter_value({_,C,N} = Key, Value, Pid) ->
  323. OldVal = ets:lookup_element(?TAB, {Key, Pid}, 3), % may fail with badarg
  324. Res = ets:insert(?TAB, {{Key, Pid}, Pid, Value}),
  325. update_aggr_counter(C, N, Value - OldVal),
  326. Res.
  327. update_counter({c,l,Ctr} = Key, Incr, Pid) when is_integer(Incr) ->
  328. Res = ets:update_counter(?TAB, {Key, Pid}, {3,Incr}),
  329. update_aggr_counter(l, Ctr, Incr),
  330. Res;
  331. update_counter({c,l,Ctr} = Key, {Incr, Threshold, SetValue}, Pid)
  332. when is_integer(Incr), is_integer(Threshold), is_integer(SetValue) ->
  333. [Prev, New] = ets:update_counter(?TAB, {Key, Pid},
  334. [{3, 0}, {3, Incr, Threshold, SetValue}]),
  335. update_aggr_counter(l, Ctr, New - Prev),
  336. New;
  337. update_counter({c,l,Ctr} = Key, Ops, Pid) when is_list(Ops) ->
  338. case ets:update_counter(?TAB, {Key, Pid},
  339. [{3, 0} | expand_ops(Ops)]) of
  340. [_] ->
  341. [];
  342. [Prev | Rest] ->
  343. [New | _] = lists:reverse(Rest),
  344. update_aggr_counter(l, Ctr, New - Prev),
  345. Rest
  346. end;
  347. update_counter(_, _, _) ->
  348. ?THROW_GPROC_ERROR(badarg).
  349. expand_ops([{Incr,Thr,SetV}|T])
  350. when is_integer(Incr), is_integer(Thr), is_integer(SetV) ->
  351. [{3, Incr, Thr, SetV}|expand_ops(T)];
  352. expand_ops([Incr|T]) when is_integer(Incr) ->
  353. [{3, Incr}|expand_ops(T)];
  354. expand_ops([]) ->
  355. [];
  356. expand_ops(_) ->
  357. ?THROW_GPROC_ERROR(badarg).
  358. update_aggr_counter(C, N, Val) ->
  359. catch ets:update_counter(?TAB, {{a,C,N},a}, {3, Val}).
  360. scan_existing_counters(Ctxt, Name) ->
  361. Head = {{{c,Ctxt,Name},'_'},'_','$1'},
  362. Cs = ets:select(?TAB, [{Head, [], ['$1']}]),
  363. lists:sum(Cs).
  364. valid_opts(Type, Default) ->
  365. Opts = get_app_env(Type, Default),
  366. check_opts(Type, Opts).
  367. check_opts(Type, Opts) when is_list(Opts) ->
  368. Check = check_option_f(Type),
  369. lists:map(fun(X) ->
  370. case Check(X) of
  371. true -> X;
  372. false ->
  373. erlang:error({illegal_option, X}, [Type, Opts])
  374. end
  375. end, Opts);
  376. check_opts(Type, Other) ->
  377. erlang:error(invalid_options, [Type, Other]).
  378. check_option_f(ets_options) -> fun check_ets_option/1;
  379. check_option_f(server_options) -> fun check_server_option/1.
  380. check_ets_option({read_concurrency , B}) -> is_boolean(B);
  381. check_ets_option({write_concurrency, B}) -> is_boolean(B);
  382. check_ets_option(_) -> false.
  383. check_server_option({priority, P}) ->
  384. %% Forbid setting priority to 'low' since that would
  385. %% surely cause problems. Unsure about 'max'...
  386. lists:member(P, [normal, high, max]);
  387. check_server_option(_) ->
  388. %% assume it's a valid spawn option
  389. true.
  390. get_app_env(Key, Default) ->
  391. case application:get_env(Key) of
  392. undefined -> Default;
  393. {ok, undefined} -> Default;
  394. {ok, Value} -> Value
  395. end.