PageRenderTime 51ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/src/gproc_dist.erl

http://github.com/esl/gproc
Erlang | 992 lines | 808 code | 92 blank | 92 comment | 37 complexity | 83a01e190639513332cab1c33367bb60 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception
  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_dist).
  23. -behaviour(gen_leader).
  24. -export([start_link/0, start_link/1,
  25. reg/1, reg/2, unreg/1,
  26. reg_or_locate/3,
  27. reg_shared/2, unreg_shared/1,
  28. monitor/2,
  29. demonitor/2,
  30. set_attributes/2,
  31. set_attributes_shared/2,
  32. mreg/2,
  33. munreg/2,
  34. set_value/2,
  35. set_value_shared/2,
  36. give_away/2,
  37. update_counter/3,
  38. update_counters/1,
  39. update_shared_counter/2,
  40. reset_counter/1]).
  41. -export([leader_call/1,
  42. leader_cast/1,
  43. sync/0,
  44. get_leader/0]).
  45. %%% internal exports
  46. -export([init/1,
  47. handle_cast/3,
  48. handle_call/4,
  49. handle_info/2, handle_info/3,
  50. handle_leader_call/4,
  51. handle_leader_cast/3,
  52. handle_DOWN/3,
  53. elected/2, % original version
  54. elected/3,
  55. surrendered/3,
  56. from_leader/3,
  57. code_change/4,
  58. terminate/2]).
  59. -include("gproc_int.hrl").
  60. -include("gproc.hrl").
  61. -define(SERVER, ?MODULE).
  62. -record(state, {
  63. always_broadcast = false,
  64. is_leader,
  65. sync_requests = []}).
  66. %% ==========================================================
  67. %% Start functions
  68. start_link() ->
  69. start_link({[node()|nodes()], []}).
  70. start_link(all) ->
  71. start_link({[node()|nodes()], [{bcast_type, all}]});
  72. start_link(Nodes) when is_list(Nodes) ->
  73. start_link({Nodes, []});
  74. start_link({Nodes, Opts}) ->
  75. SpawnOpts = gproc_lib:valid_opts(server_options, []),
  76. gen_leader:start_link(
  77. ?SERVER, Nodes, Opts, ?MODULE, [], [{spawn_opt, SpawnOpts}]).
  78. %% ==========================================================
  79. %% API
  80. %% {@see gproc:reg/1}
  81. %%
  82. reg(Key) ->
  83. reg(Key, gproc:default(Key)).
  84. %% {@see gproc:reg_or_locate/2}
  85. %%
  86. reg_or_locate({n,g,_} = Key, Value, Pid) when is_pid(Pid) ->
  87. leader_call({reg_or_locate, Key, Value, Pid});
  88. reg_or_locate({n,g,_} = Key, Value, F) when is_function(F, 0) ->
  89. MyGroupLeader = group_leader(),
  90. leader_call({reg_or_locate, Key, Value,
  91. fun() ->
  92. %% leader will spawn on caller's node
  93. group_leader(MyGroupLeader, self()),
  94. F()
  95. end});
  96. reg_or_locate(_, _, _) ->
  97. ?THROW_GPROC_ERROR(badarg).
  98. %%% @spec({Class,Scope, Key}, Value) -> true
  99. %%% @doc
  100. %%% Class = n - unique name
  101. %%% | p - non-unique property
  102. %%% | c - counter
  103. %%% | a - aggregated counter
  104. %%% Scope = l | g (global or local)
  105. %%% @end
  106. reg({_,g,_} = Key, Value) ->
  107. %% anything global
  108. leader_call({reg, Key, Value, self()});
  109. reg(_, _) ->
  110. ?THROW_GPROC_ERROR(badarg).
  111. reg_shared({_,g,_} = Key, Value) ->
  112. leader_call({reg, Key, Value, shared});
  113. reg_shared(_, _) ->
  114. ?THROW_GPROC_ERROR(badarg).
  115. monitor({_,g,_} = Key, Type) when Type==info;
  116. Type==follow;
  117. Type==standby ->
  118. leader_call({monitor, Key, self(), Type});
  119. monitor(_, _) ->
  120. ?THROW_GPROC_ERROR(badarg).
  121. demonitor({_,g,_} = Key, Ref) ->
  122. leader_call({demonitor, Key, self(), Ref});
  123. demonitor(_, _) ->
  124. ?THROW_GPROC_ERROR(badarg).
  125. set_attributes({_,g,_} = Key, Attrs) ->
  126. leader_call({set_attributes, Key, Attrs, self()});
  127. set_attributes(_, _) ->
  128. ?THROW_GPROC_ERROR(badarg).
  129. set_attributes_shared({_,g,_} = Key, Attrs) ->
  130. leader_call({set_attributes, Key, Attrs, shared});
  131. set_attributes_shared(_, _) ->
  132. ?THROW_GPROC_ERROR(badarg).
  133. mreg(T, KVL) ->
  134. if is_list(KVL) -> leader_call({mreg, T, g, KVL, self()});
  135. true -> ?THROW_GPROC_ERROR(badarg)
  136. end.
  137. munreg(T, Keys) ->
  138. if is_list(Keys) -> leader_call({munreg, T, g, Keys, self()});
  139. true -> ?THROW_GPROC_ERROR(badarg)
  140. end.
  141. unreg({_,g,_} = Key) ->
  142. leader_call({unreg, Key, self()});
  143. unreg(_) ->
  144. ?THROW_GPROC_ERROR(badarg).
  145. unreg_shared({T,g,_} = Key) when T==c; T==a ->
  146. leader_call({unreg, Key, shared});
  147. unreg_shared(_) ->
  148. ?THROW_GPROC_ERROR(badarg).
  149. set_value({T,g,_} = Key, Value) when T==a; T==c ->
  150. if is_integer(Value) ->
  151. leader_call({set, Key, Value, self()});
  152. true ->
  153. ?THROW_GPROC_ERROR(badarg)
  154. end;
  155. set_value({_,g,_} = Key, Value) ->
  156. leader_call({set, Key, Value, self()});
  157. set_value(_, _) ->
  158. ?THROW_GPROC_ERROR(badarg).
  159. set_value_shared({T,g,_} = Key, Value) when T==a; T==c; T==p ->
  160. leader_call({set, Key, Value, shared});
  161. set_value_shared(_, _) ->
  162. ?THROW_GPROC_ERROR(badarg).
  163. give_away({_,g,_} = Key, To) ->
  164. leader_call({give_away, Key, To, self()}).
  165. update_counter({T,g,_} = Key, Pid, Incr) when is_integer(Incr), T==c;
  166. is_integer(Incr), T==n ->
  167. leader_call({update_counter, Key, Incr, Pid});
  168. update_counter(_, _, _) ->
  169. ?THROW_GPROC_ERROR(badarg).
  170. update_counters(List) when is_list(List) ->
  171. leader_call({update_counters, List});
  172. update_counters(_) ->
  173. ?THROW_GPROC_ERROR(badarg).
  174. update_shared_counter({c,g,_} = Key, Incr) when is_integer(Incr) ->
  175. leader_call({update_counter, Key, Incr, shared});
  176. update_shared_counter(_, _) ->
  177. ?THROW_GPROC_ERROR(badarg).
  178. reset_counter({c,g,_} = Key) ->
  179. leader_call({reset_counter, Key, self()});
  180. reset_counter(_) ->
  181. ?THROW_GPROC_ERROR(badarg).
  182. %% @spec sync() -> true
  183. %% @doc Synchronize with the gproc leader
  184. %%
  185. %% This function can be used to ensure that data has been replicated from the
  186. %% leader to the current node. It does so by asking the leader to ping all
  187. %% live participating nodes. The call will return `true' when all these nodes
  188. %% have either responded or died. In the special case where the leader dies
  189. %% during an ongoing sync, the call will fail with a timeout exception.
  190. %% (Actually, it should be a `leader_died' exception; more study needed to find
  191. %% out why gen_leader times out in this situation, rather than reporting that
  192. %% the leader died.)
  193. %% @end
  194. %%
  195. sync() ->
  196. leader_call(sync).
  197. %% @spec get_leader() -> node()
  198. %% @doc Returns the node of the current gproc leader.
  199. %% @end
  200. get_leader() ->
  201. GenLeader = gen_leader,
  202. GenLeader:call(?MODULE, get_leader).
  203. %% ==========================================================
  204. %% Server-side
  205. handle_cast(_Msg, S, _) ->
  206. {stop, unknown_cast, S}.
  207. handle_call(get_leader, _, S, E) ->
  208. {reply, gen_leader:leader_node(E), S};
  209. handle_call(_, _, S, _) ->
  210. {reply, badarg, S}.
  211. handle_info({'DOWN', _MRef, process, Pid, _}, S) ->
  212. ets:delete(?TAB, {Pid, g}),
  213. leader_cast({pid_is_DOWN, Pid}),
  214. {ok, S};
  215. handle_info(_, S) ->
  216. {ok, S}.
  217. handle_info(Msg, S, _E) ->
  218. handle_info(Msg, S).
  219. elected(S, _E) ->
  220. {ok, {globals,globs()}, S#state{is_leader = true}}.
  221. elected(S, _E, undefined) ->
  222. %% I have become leader; full synch
  223. {ok, {globals, globs()}, S#state{is_leader = true}};
  224. elected(S, _E, _Node) ->
  225. Synch = {globals, globs()},
  226. if not S#state.always_broadcast ->
  227. %% Another node recognized us as the leader.
  228. %% Don't broadcast all data to everyone else
  229. {reply, Synch, S};
  230. true ->
  231. %% Main reason for doing this is if we are using a gen_leader
  232. %% that doesn't support the 'reply' return value
  233. {ok, Synch, S}
  234. end.
  235. globs() ->
  236. Gs = ets:select(?TAB, [{{{{'_',g,'_'},'_'},'_','_'},[],['$_']}]),
  237. As = ets:select(?TAB, [{{{'$1',{'_',g,'_'}}, '$2'},[],['$_']}]),
  238. _ = [gproc_lib:ensure_monitor(Pid, g) || {_, Pid, _} <- Gs],
  239. Gs ++ As.
  240. surrendered(#state{is_leader = true} = S, {globals, Globs}, _E) ->
  241. %% Leader conflict!
  242. surrendered_1(Globs),
  243. {ok, S#state{is_leader = false}};
  244. surrendered(S, {globals, Globs}, _E) ->
  245. %% globals from this node should be more correct in our table than
  246. %% in the leader's
  247. surrendered_1(Globs),
  248. {ok, S#state{is_leader = false}}.
  249. handle_DOWN(Node, S, _E) ->
  250. S1 = check_sync_requests(Node, S),
  251. Head = {{{'_',g,'_'},'_'},'$1','_'},
  252. Gs = [{'==', {node,'$1'},Node}],
  253. Globs = ets:select(?TAB, [{Head, Gs, [{{{element,1,{element,1,'$_'}},
  254. {element,2,'$_'}}}]}]),
  255. case process_globals(Globs) of
  256. [] ->
  257. {ok, S1};
  258. Broadcast ->
  259. {ok, Broadcast, S1}
  260. end.
  261. check_sync_requests(Node, #state{sync_requests = SReqs} = S) ->
  262. SReqs1 = lists:flatmap(
  263. fun({From, Ns}) ->
  264. case Ns -- [Node] of
  265. [] ->
  266. gen_leader:reply(From, {leader, reply, true}),
  267. [];
  268. Ns1 ->
  269. [{From, Ns1}]
  270. end
  271. end, SReqs),
  272. S#state{sync_requests = SReqs1}.
  273. handle_leader_call(sync, From, #state{sync_requests = SReqs} = S, E) ->
  274. GenLeader = gen_leader,
  275. case GenLeader:alive(E) -- [node()] of
  276. [] ->
  277. {reply, true, S};
  278. Alive ->
  279. GenLeader:broadcast({from_leader, {sync, From}}, Alive, E),
  280. {noreply, S#state{sync_requests = [{From, Alive}|SReqs]}}
  281. end;
  282. handle_leader_call({reg, {_C,g,_Name} = K, Value, Pid}, _From, S, _E) ->
  283. case gproc_lib:insert_reg(K, Value, Pid, g) of
  284. false ->
  285. {reply, badarg, S};
  286. true ->
  287. _ = gproc_lib:ensure_monitor(Pid,g),
  288. Vals = mk_broadcast_insert_vals([{K, Pid, Value}]),
  289. %% Vals =
  290. %% if C == a ->
  291. %% ets:lookup(?TAB, {K,a});
  292. %% C == c ->
  293. %% [{{K,Pid},Pid,Value} | ets:lookup(?TAB,{{a,g,Name},a})];
  294. %% C == n ->
  295. %% [{{K,n},Pid,Value}];
  296. %% true ->
  297. %% [{{K,Pid},Pid,Value}]
  298. %% end,
  299. {reply, true, [{insert, Vals}], S}
  300. end;
  301. handle_leader_call({monitor, {T,g,_} = K, MPid, Type}, _From, S, _E) when T==n;
  302. T==a ->
  303. case ets:lookup(?TAB, {K, T}) of
  304. [{_, Pid, _}] ->
  305. Opts = get_opts(Pid, K),
  306. Ref = make_ref(),
  307. Opts1 = gproc_lib:add_monitor(Opts, MPid, Ref, Type),
  308. _ = gproc_lib:ensure_monitor(MPid, g),
  309. Obj = {{Pid,K}, Opts1},
  310. Rev = {{MPid,K}, []},
  311. ets:insert(?TAB, [Obj, Rev]),
  312. {reply, Ref, [{insert, [Obj, Rev]}], S};
  313. LookupRes ->
  314. Ref = make_ref(),
  315. case Type of
  316. standby ->
  317. Event = {failover, MPid},
  318. Msgs = insert_reg(LookupRes, K, undefined, MPid, Event),
  319. Obj = {{K,T}, MPid, undefined},
  320. Rev = {{MPid,K}, []},
  321. ets:insert(?TAB, [Obj, Rev]),
  322. MPid ! {gproc, {failover,MPid}, Ref, K},
  323. {reply, Ref, [{insert, [Obj, Rev]},
  324. {notify, Msgs}], S};
  325. follow ->
  326. case LookupRes of
  327. [{_, Waiters}] ->
  328. add_follow_to_waiters(Waiters, K, MPid, Ref, S);
  329. [] ->
  330. add_follow_to_waiters([], K, MPid, Ref, S);
  331. [{_, Pid, _}] ->
  332. case ets:lookup(?TAB, {Pid,K}) of
  333. [{_, Opts}] when is_list(Opts) ->
  334. Opts1 = gproc_lib:add_monitor(
  335. Opts, MPid, Ref, follow),
  336. ets:insert(?TAB, {{Pid,K}, Opts1}),
  337. {reply, Ref,
  338. [{insert, [{{Pid,K}, Opts1}]}], S}
  339. end
  340. end;
  341. _ ->
  342. MPid ! {gproc, unreg, Ref, K},
  343. {reply, Ref, S}
  344. end
  345. end;
  346. handle_leader_call({demonitor, {T,g,_} = K, MPid, Ref}, _From, S, _E) ->
  347. case ets:lookup(?TAB, {K,T}) of
  348. [{_, Pid, _}] ->
  349. Opts = get_opts(Pid, K),
  350. Opts1 = gproc_lib:remove_monitors(Opts, MPid, Ref),
  351. Obj = {{Pid,K}, Opts1},
  352. ets:insert(?TAB, Obj),
  353. ets:delete(?TAB, {MPid, K}),
  354. {reply, ok, [{delete, [{MPid,K}]},
  355. {insert, [Obj]}], S};
  356. [{Key, Waiters}] ->
  357. NewWaiters = [W || W <- Waiters,
  358. W =/= {MPid, Ref, follow}],
  359. {reply, ok, [{insert, [{Key, NewWaiters}]}], S};
  360. _ ->
  361. {reply, ok, S}
  362. end;
  363. handle_leader_call({set_attributes, {_,g,_} = K, Attrs, Pid}, _From, S, _E) ->
  364. case gproc_lib:insert_attr(K, Attrs, Pid, g) of
  365. false ->
  366. {reply, badarg, S};
  367. NewAttrs when is_list(NewAttrs) ->
  368. {reply, true, [{insert, [{{Pid,K}, NewAttrs}]}], S}
  369. end;
  370. handle_leader_call({reg_or_locate, {n,g,_} = K, Value, P},
  371. {FromPid, _}, S, _E) ->
  372. FromNode = node(FromPid),
  373. Reg = fun() ->
  374. Pid = if is_function(P, 0) ->
  375. spawn(FromNode, P);
  376. is_pid(P) ->
  377. P
  378. end,
  379. case gproc_lib:insert_reg(K, Value, Pid, g) of
  380. true ->
  381. _ = gproc_lib:ensure_monitor(Pid,g),
  382. Vals = [{{K,n},Pid,Value}],
  383. {reply, {Pid, Value}, [{insert, Vals}], S};
  384. false ->
  385. {reply, badarg, S}
  386. end
  387. end,
  388. case ets:lookup(?TAB, {K, n}) of
  389. [] ->
  390. Reg();
  391. [{_, _Waiters}] ->
  392. Reg();
  393. [{_, OtherPid, OtherVal}] ->
  394. {reply, {OtherPid, OtherVal}, S}
  395. end;
  396. handle_leader_call({update_counter, {T,g,_Ctr} = Key, Incr, Pid}, _From, S, _E)
  397. when is_integer(Incr), T==c;
  398. is_integer(Incr), T==n ->
  399. try New = ets:update_counter(?TAB, {Key, Pid}, {3,Incr}),
  400. RealPid = case Pid of
  401. n -> ets:lookup_element(?TAB, {Key,Pid}, 2);
  402. shared -> shared;
  403. P when is_pid(P) -> P
  404. end,
  405. Vals = [{{Key,Pid},RealPid,New} | update_aggr_counter(Key, Incr)],
  406. {reply, New, [{insert, Vals}], S}
  407. catch
  408. error:_ ->
  409. {reply, badarg, S}
  410. end;
  411. handle_leader_call({update_counters, Cs}, _From, S, _E) ->
  412. try {Replies, Vals} = batch_update_counters(Cs),
  413. {reply, Replies, [{insert, Vals}], S}
  414. catch
  415. error:_ ->
  416. {reply, badarg, S}
  417. end;
  418. handle_leader_call({reset_counter, {c,g,_Ctr} = Key, Pid}, _From, S, _E) ->
  419. try Current = ets:lookup_element(?TAB, {Key, Pid}, 3),
  420. Initial = case ets:lookup_element(?TAB, {Pid, Key}, 2) of
  421. r -> 0;
  422. Opts when is_list(Opts) ->
  423. proplists:get_value(initial, Opts, 0)
  424. end,
  425. Incr = Initial - Current,
  426. New = ets:update_counter(?TAB, {Key, Pid}, {3, Incr}),
  427. Vals = [{{Key,Pid},Pid,New} | update_aggr_counter(Key, Incr)],
  428. {reply, {Current, New}, [{insert, Vals}], S}
  429. catch
  430. error:_R ->
  431. io:fwrite("reset_counter failed: ~p~n~p~n", [_R, erlang:get_stacktrace()]),
  432. {reply, badarg, S}
  433. end;
  434. handle_leader_call({unreg, {T,g,Name} = K, Pid}, _From, S, _E) ->
  435. Key = if T == n; T == a -> {K,T};
  436. true -> {K, Pid}
  437. end,
  438. case ets:member(?TAB, Key) of
  439. true ->
  440. _ = gproc_lib:remove_reg(K, Pid, unreg),
  441. if T == c ->
  442. case ets:lookup(?TAB, {{a,g,Name},a}) of
  443. [Aggr] ->
  444. %% updated by remove_reg/3
  445. {reply, true, [{delete,[Key, {Pid,K}]},
  446. {insert, [Aggr]}], S};
  447. [] ->
  448. {reply, true, [{delete, [Key, {Pid,K}]}], S}
  449. end;
  450. true ->
  451. {reply, true, [{notify, [{K, Pid, unreg}]},
  452. {delete, [Key, {Pid,K}]}], S}
  453. end;
  454. false ->
  455. {reply, badarg, S}
  456. end;
  457. handle_leader_call({give_away, {T,g,_} = K, To, Pid}, _From, S, _E)
  458. when T == a; T == n ->
  459. Key = {K, T},
  460. case ets:lookup(?TAB, Key) of
  461. [{_, Pid, Value}] ->
  462. Opts = get_opts(Pid, K),
  463. case pid_to_give_away_to(To) of
  464. Pid ->
  465. {reply, Pid, S};
  466. ToPid when is_pid(ToPid) ->
  467. ets:insert(?TAB, [{Key, ToPid, Value},
  468. {{ToPid,K}, Opts}]),
  469. _ = gproc_lib:ensure_monitor(ToPid, g),
  470. Rev = {Pid, K},
  471. ets:delete(?TAB, Rev),
  472. gproc_lib:notify({migrated, ToPid}, K, Opts),
  473. {reply, ToPid, [{insert, [{Key, ToPid, Value}]},
  474. {notify, [{K, Pid, {migrated, ToPid}}]},
  475. {delete, [Rev]}], S};
  476. undefined ->
  477. ets:delete(?TAB, Key),
  478. Rev = {Pid, K},
  479. ets:delete(?TAB, Rev),
  480. gproc_lib:notify(unreg, K, Opts),
  481. {reply, undefined, [{notify, [{K, Pid, unreg}]},
  482. {delete, [Key, Rev]}], S}
  483. end;
  484. _ ->
  485. {reply, badarg, S}
  486. end;
  487. handle_leader_call({mreg, T, g, L, Pid}, _From, S, _E) ->
  488. if T==p; T==n ->
  489. try gproc_lib:insert_many(T, g, L, Pid) of
  490. {true,Objs} -> {reply, true, [{insert,Objs}], S};
  491. false -> {reply, badarg, S}
  492. catch
  493. error:_ -> {reply, badarg, S}
  494. end;
  495. true -> {reply, badarg, S}
  496. end;
  497. handle_leader_call({munreg, T, g, L, Pid}, _From, S, _E) ->
  498. try gproc_lib:remove_many(T, g, L, Pid) of
  499. [] ->
  500. {reply, true, S};
  501. Objs ->
  502. {reply, true, [{delete, Objs}], S}
  503. catch
  504. error:_ -> {reply, badarg, S}
  505. end;
  506. handle_leader_call({set,{T,g,N} =K,V,Pid}, _From, S, _E) ->
  507. if T == a ->
  508. if is_integer(V) ->
  509. case gproc_lib:do_set_value(K, V, Pid) of
  510. true -> {reply, true, [{insert,[{{K,T},Pid,V}]}], S};
  511. false -> {reply, badarg, S}
  512. end
  513. end;
  514. T == c ->
  515. try gproc_lib:do_set_counter_value(K, V, Pid),
  516. AKey = {{a,g,N},a},
  517. Aggr = ets:lookup(?TAB, AKey), % may be []
  518. {reply, true, [{insert, [{{K,Pid},Pid,V} | Aggr]}], S}
  519. catch
  520. error:_ ->
  521. {reply, badarg, S}
  522. end;
  523. true ->
  524. case gproc_lib:do_set_value(K, V, Pid) of
  525. true ->
  526. Obj = if T==n -> {{K, T}, Pid, V};
  527. true -> {{K, Pid}, Pid, V}
  528. end,
  529. {reply, true, [{insert,[Obj]}], S};
  530. false ->
  531. {reply, badarg, S}
  532. end
  533. end;
  534. handle_leader_call({await, Key, Pid}, {_,Ref} = From, S, _E) ->
  535. %% The pid in _From is of the gen_leader instance that forwarded the
  536. %% call - not of the client. This is why the Pid is explicitly passed.
  537. %% case gproc_lib:await(Key, {Pid,Ref}) of
  538. case gproc_lib:await(Key, Pid, From) of
  539. {reply, {Ref, {K, P, V}}} ->
  540. {reply, {Ref, {K, P, V}}, S};
  541. {reply, Reply, Insert} ->
  542. {reply, Reply, [{insert, Insert}], S}
  543. end;
  544. handle_leader_call(_, _, S, _E) ->
  545. {reply, badarg, S}.
  546. handle_leader_cast({sync_reply, Node, Ref}, S, _E) ->
  547. #state{sync_requests = SReqs} = S,
  548. case lists:keyfind(Ref, 1, SReqs) of
  549. false ->
  550. %% This should never happen, except perhaps if the leader who
  551. %% received the sync request died, and the new leader gets the
  552. %% sync reply. In that case, we trust that the client has been
  553. %% notified anyway, and ignore the message.
  554. {ok, S};
  555. {_, Ns} ->
  556. case lists:delete(Node, Ns) of
  557. [] ->
  558. gen_leader:reply(Ref, {leader, reply, true}),
  559. {ok, S#state{sync_requests = lists:keydelete(Ref,1,SReqs)}};
  560. Ns1 ->
  561. SReqs1 = lists:keyreplace(Ref, 1, SReqs, {Ref, Ns1}),
  562. {ok, S#state{sync_requests = SReqs1}}
  563. end
  564. end;
  565. handle_leader_cast({add_globals, Missing}, S, _E) ->
  566. %% This is an audit message: a peer (non-leader) had info about granted
  567. %% global resources that we didn't know of when we became leader.
  568. %% This could happen due to a race condition when the old leader died.
  569. Update = insert_globals(Missing),
  570. {ok, [{insert, Update}], S};
  571. handle_leader_cast({remove_globals, Globals}, S, _E) ->
  572. delete_globals(Globals),
  573. {ok, S};
  574. handle_leader_cast({cancel_wait, Pid, {T,_,_} = Key, Ref}, S, _E) ->
  575. case ets:lookup(?TAB, {Key, T}) of
  576. [{_, Waiters}] ->
  577. Ops = gproc_lib:remove_wait(Key, Pid, Ref, Waiters),
  578. {ok, Ops, S};
  579. _ ->
  580. {ok, [], S}
  581. end;
  582. handle_leader_cast({cancel_wait_or_monitor, Pid, {T,_,_} = Key}, S, _E) ->
  583. case ets:lookup(?TAB, {Key, T}) of
  584. [{_, Waiters}] ->
  585. Ops = gproc_lib:remove_wait(Key, Pid, all, Waiters),
  586. {ok, Ops, S};
  587. [{_, OtherPid, _}] ->
  588. Ops = gproc_lib:remove_monitors(Key, OtherPid, Pid),
  589. {ok, Ops, S}
  590. end;
  591. handle_leader_cast({pid_is_DOWN, Pid}, S, _E) ->
  592. Globals = ets:select(?TAB, [{{{Pid,'$1'}, '_'},
  593. [{'==',{element,2,'$1'},g}],[{{'$1',Pid}}]}]),
  594. ets:delete(?TAB, {Pid,g}),
  595. case process_globals(Globals) of
  596. [] ->
  597. {ok, S};
  598. Broadcast ->
  599. {ok, Broadcast, S}
  600. end.
  601. mk_broadcast_insert_vals(Objs) ->
  602. lists:flatmap(
  603. fun({{C, g, Name} = K, Pid, Value}) ->
  604. if C == a ->
  605. ets:lookup(?TAB, {K,a}) ++ ets:lookup(?TAB, {Pid,K});
  606. C == c ->
  607. [{{K,Pid},Pid,Value} | ets:lookup(?TAB,{{a,g,Name},a})]
  608. ++ ets:lookup(?TAB, {Pid,K});
  609. C == n ->
  610. [{{K,n},Pid,Value}| ets:lookup(?TAB, {Pid,K})];
  611. true ->
  612. [{{K,Pid},Pid,Value} | ets:lookup(?TAB, {Pid,K})]
  613. end
  614. end, Objs).
  615. process_globals(Globals) ->
  616. {Modified, Notifications} =
  617. lists:foldl(
  618. fun({{T,_,_} = Key, Pid}, A) when T==n; T==a ->
  619. case ets:lookup(?TAB, {Pid,Key}) of
  620. [{_, Opts}] when is_list(Opts) ->
  621. maybe_failover(Key, Pid, Opts, A);
  622. _ ->
  623. A
  624. end;
  625. ({{T,_,_} = Key, Pid}, {MA,NA}) ->
  626. MA1 = case T of
  627. c ->
  628. Incr = ets:lookup_element(?TAB, {Key,Pid}, 3),
  629. update_aggr_counter(Key, -Incr) ++ MA;
  630. _ ->
  631. MA
  632. end,
  633. N = remove_entry(Key, Pid, unreg),
  634. {MA1, N ++ NA}
  635. end, {[],[]}, Globals),
  636. [{insert, Modified} || Modified =/= []] ++
  637. [{notify, Notifications} || Notifications =/= []] ++
  638. [{delete, Globals} || Globals =/= []].
  639. maybe_failover({T,_,_} = Key, Pid, Opts, {MAcc, NAcc}) ->
  640. Opts = get_opts(Pid, Key),
  641. case filter_standbys(gproc_lib:standbys(Opts)) of
  642. [] ->
  643. Notify = remove_entry(Key, Pid, unreg),
  644. {MAcc, Notify ++ NAcc};
  645. [{ToPid,Ref,_}|_] ->
  646. Value = case ets:lookup(?TAB, {Key,T}) of
  647. [{_, _, V}] -> V;
  648. _ -> undefined
  649. end,
  650. Notify = remove_rev_entry(Opts, Pid, Key, {failover, ToPid}),
  651. Opts1 = gproc_lib:remove_monitor(Opts, ToPid, Ref),
  652. _ = gproc_lib:ensure_monitor(ToPid, g),
  653. NewReg = {{Key,T}, ToPid, Value},
  654. NewRev = {{ToPid, Key}, Opts1},
  655. ets:insert(?TAB, [NewReg, NewRev]),
  656. {[NewReg, NewRev | MAcc], Notify ++ NAcc}
  657. end.
  658. filter_standbys(SBs) ->
  659. filter_standbys(SBs, [node()|nodes()]).
  660. filter_standbys([{Pid,_,_} = H|T], Nodes) ->
  661. case lists:member(node(Pid), Nodes) of
  662. true ->
  663. [H|T];
  664. false ->
  665. filter_standbys(T, Nodes)
  666. end;
  667. filter_standbys([], _) ->
  668. [].
  669. remove_entry(Key, Pid, Event) ->
  670. K = ets_key(Key, Pid),
  671. ets:delete(?TAB, K),
  672. remove_rev_entry(get_opts(Pid, Key), Pid, Key, Event).
  673. remove_rev_entry(Opts, Pid, {T,g,_} = K, Event) when T==n; T==a ->
  674. Key = {Pid, K},
  675. gproc_lib:notify(Event, K, Opts),
  676. ets:delete(?TAB, Key),
  677. [{K, Pid, Event}];
  678. remove_rev_entry(_, Pid, K, _Event) ->
  679. ets:delete(?TAB, {Pid, K}),
  680. [].
  681. get_opts(Pid, K) ->
  682. case ets:lookup(?TAB, {Pid, K}) of
  683. [] -> [];
  684. [{_, r}] -> [];
  685. [{_, Opts}] -> Opts
  686. end.
  687. code_change(_FromVsn, S, _Extra, _E) ->
  688. {ok, S}.
  689. terminate(_Reason, _S) ->
  690. ok.
  691. from_leader({sync, Ref}, S, _E) ->
  692. gen_leader:leader_cast(?MODULE, {sync_reply, node(), Ref}),
  693. {ok, S};
  694. from_leader(Ops, S, _E) ->
  695. lists:foreach(
  696. fun({delete, Globals}) ->
  697. delete_globals(Globals);
  698. ({insert, Globals}) ->
  699. _ = insert_globals(Globals);
  700. ({notify, Events}) ->
  701. do_notify(Events)
  702. end, Ops),
  703. {ok, S}.
  704. insert_globals(Globals) ->
  705. lists:foldl(
  706. fun({{{_,_,_} = Key,_}, Pid, _} = Obj, A) ->
  707. ets:insert(?TAB, Obj),
  708. ets:insert_new(?TAB, {{Pid,Key}, []}),
  709. gproc_lib:ensure_monitor(Pid,g),
  710. A;
  711. ({{P,_K}, Opts} = Obj, A) when is_pid(P), is_list(Opts),Opts =/= [] ->
  712. ets:insert(?TAB, Obj),
  713. gproc_lib:ensure_monitor(P,g),
  714. [Obj] ++ A;
  715. (_Other, A) ->
  716. A
  717. end, Globals, Globals).
  718. delete_globals(Globals) ->
  719. lists:foreach(
  720. fun({{_,g,_},T} = K) when is_atom(T) ->
  721. ets:delete(?TAB, K);
  722. ({Key, Pid}) when is_pid(Pid); Pid==shared ->
  723. ets:delete(?TAB, {Key, Pid});
  724. ({Pid, Key}) when is_pid(Pid); Pid==shared ->
  725. ets:delete(?TAB, {Pid, Key})
  726. end, Globals).
  727. do_notify([{P, Msg}|T]) when is_pid(P) ->
  728. P ! Msg,
  729. do_notify(T);
  730. do_notify([{K, P, E}|T]) ->
  731. case ets:lookup(?TAB, {P,K}) of
  732. [{_, Opts}] when is_list(Opts) ->
  733. gproc_lib:notify(E, K, Opts);
  734. _ ->
  735. do_notify(T)
  736. end;
  737. do_notify([]) ->
  738. ok.
  739. ets_key({T,_,_} = K, _) when T==n; T==a ->
  740. {K, T};
  741. ets_key(K, Pid) ->
  742. {K, Pid}.
  743. leader_call(Req) ->
  744. case gen_leader:leader_call(?MODULE, Req) of
  745. badarg -> ?THROW_GPROC_ERROR(badarg);
  746. Reply -> Reply
  747. end.
  748. leader_cast(Msg) ->
  749. gen_leader:leader_cast(?MODULE, Msg).
  750. init(Opts) ->
  751. S0 = #state{},
  752. AlwaysBcast = proplists:get_value(always_broadcast, Opts,
  753. S0#state.always_broadcast),
  754. {ok, #state{always_broadcast = AlwaysBcast}}.
  755. surrendered_1(Globs) ->
  756. My_local_globs =
  757. ets:select(?TAB, [{{{{'_',g,'_'},'_'},'$1', '$2'},
  758. [{'==', {node,'$1'}, node()}],
  759. [{{ {element,1,{element,1,'$_'}}, '$1', '$2' }}]}]),
  760. _ = [gproc_lib:ensure_monitor(Pid, g) || {_, Pid, _} <- My_local_globs],
  761. %% remove all remote globals.
  762. ets:select_delete(?TAB, [{{{{'_',g,'_'},'_'}, '$1', '_'},
  763. [{'=/=', {node,'$1'}, node()}],
  764. [true]},
  765. {{{'$1',{'_',g,'_'}}, '_'},
  766. [{'=/=', {node,'$1'}, node()}],
  767. [true]}]),
  768. %% insert new non-local globals, collect the leader's version of
  769. %% what my globals are
  770. Ldr_local_globs =
  771. lists:foldl(
  772. fun({{Key,_}=K, Pid, V}, Acc) when node(Pid) =/= node() ->
  773. ets:insert(?TAB, {K, Pid, V}),
  774. _ = gproc_lib:ensure_monitor(Pid, g),
  775. ets:insert_new(?TAB, {{Pid,Key}, []}),
  776. Acc;
  777. ({{_Pid,_}=K, Opts}, Acc) -> % when node(Pid) =/= node() ->
  778. ets:insert(?TAB, {K, Opts}),
  779. Acc;
  780. ({_, Pid, _} = Obj, Acc) when node(Pid) == node() ->
  781. [Obj|Acc]
  782. end, [], Globs),
  783. case [{K,P,V} || {K,P,V} <- My_local_globs,
  784. is_pid(P) andalso
  785. not(lists:keymember(K, 1, Ldr_local_globs))] of
  786. [] ->
  787. %% phew! We have the same picture
  788. ok;
  789. [_|_] = Missing ->
  790. %% This is very unlikely, I think
  791. leader_cast({add_globals, mk_broadcast_insert_vals(Missing)})
  792. end,
  793. case [{K,P} || {K,P,_} <- Ldr_local_globs,
  794. is_pid(P) andalso
  795. not(lists:keymember(K, 1, My_local_globs))] of
  796. [] ->
  797. ok;
  798. [_|_] = Remove ->
  799. leader_cast({remove_globals, Remove})
  800. end.
  801. batch_update_counters(Cs) ->
  802. batch_update_counters(Cs, [], []).
  803. batch_update_counters([{{c,g,_} = Key, Pid, Incr}|T], Returns, Updates) ->
  804. case update_counter_g(Key, Incr, Pid) of
  805. [{_,_,_} = A, {_, _, V} = C] ->
  806. batch_update_counters(T, [{Key,Pid,V}|Returns], add_object(
  807. A, add_object(C, Updates)));
  808. [{_, _, V} = C] ->
  809. batch_update_counters(T, [{Key,Pid,V}|Returns], add_object(C, Updates))
  810. end;
  811. batch_update_counters([], Returns, Updates) ->
  812. {lists:reverse(Returns), Updates}.
  813. add_object({K,P,_} = Obj, [{K,P,_} | T]) ->
  814. [Obj | T];
  815. add_object(Obj, [H|T]) ->
  816. [H | add_object(Obj, T)];
  817. add_object(Obj, []) ->
  818. [Obj].
  819. update_counter_g({c,g,_} = Key, Incr, Pid) when is_integer(Incr) ->
  820. Res = ets:update_counter(?TAB, {Key, Pid}, {3,Incr}),
  821. update_aggr_counter(Key, Incr, [{{Key,Pid},Pid,Res}]);
  822. update_counter_g({c,g,_} = Key, {Incr, Threshold, SetValue}, Pid)
  823. when is_integer(Incr), is_integer(Threshold), is_integer(SetValue) ->
  824. [Prev, New] = ets:update_counter(?TAB, {Key, Pid},
  825. [{3, 0}, {3, Incr, Threshold, SetValue}]),
  826. update_aggr_counter(Key, New - Prev, [{{Key,Pid},Pid,New}]);
  827. update_counter_g({c,g,_} = Key, Ops, Pid) when is_list(Ops) ->
  828. case ets:update_counter(?TAB, {Key, Pid},
  829. [{3, 0} | expand_ops(Ops)]) of
  830. [_] ->
  831. [];
  832. [Prev | Rest] ->
  833. [New | _] = lists:reverse(Rest),
  834. update_aggr_counter(Key, New - Prev, [{Key, Pid, Rest}])
  835. end;
  836. update_counter_g(_, _, _) ->
  837. ?THROW_GPROC_ERROR(badarg).
  838. expand_ops([{Incr,Thr,SetV}|T])
  839. when is_integer(Incr), is_integer(Thr), is_integer(SetV) ->
  840. [{3, Incr, Thr, SetV}|expand_ops(T)];
  841. expand_ops([Incr|T]) when is_integer(Incr) ->
  842. [{3, Incr}|expand_ops(T)];
  843. expand_ops([]) ->
  844. [];
  845. expand_ops(_) ->
  846. ?THROW_GPROC_ERROR(badarg).
  847. update_aggr_counter({n,_,_}, _) ->
  848. [];
  849. update_aggr_counter(Key, Incr) ->
  850. update_aggr_counter(Key, Incr, []).
  851. update_aggr_counter({c,g,Ctr}, Incr, Acc) ->
  852. Key = {{a,g,Ctr},a},
  853. case ets:lookup(?TAB, Key) of
  854. [] ->
  855. Acc;
  856. [{K, Pid, Prev}] ->
  857. New = {K, Pid, Prev+Incr},
  858. ets:insert(?TAB, New),
  859. [New|Acc]
  860. end.
  861. pid_to_give_away_to(P) when is_pid(P) ->
  862. P;
  863. pid_to_give_away_to({T,g,_} = Key) when T==n; T==a ->
  864. case ets:lookup(?TAB, {Key, T}) of
  865. [{_, Pid, _}] ->
  866. Pid;
  867. _ ->
  868. undefined
  869. end.
  870. insert_reg([{_, Waiters}], K, Val, Pid, Event) ->
  871. gproc_lib:insert_reg(K, Val, Pid, g, []),
  872. tell_waiters(Waiters, K, Pid, Val, Event).
  873. tell_waiters([{P,R}|T], K, Pid, V, Event) ->
  874. Msg = {gproc, R, registered, {K, Pid, V}},
  875. if node(P) == node() ->
  876. P ! Msg;
  877. true ->
  878. [{P, Msg} | tell_waiters(T, K, Pid, V, Event)]
  879. end;
  880. tell_waiters([{P,R,follow}|T], K, Pid, V, Event) ->
  881. Msg = {gproc, Event, R, K},
  882. if node(P) == node() ->
  883. P ! Msg;
  884. true ->
  885. [{P, Msg} | tell_waiters(T, K, Pid, V, Event)]
  886. end;
  887. tell_waiters([], _, _, _, _) ->
  888. [].
  889. add_follow_to_waiters(Waiters, {T,_,_} = K, Pid, Ref, S) ->
  890. Obj = {{K,T}, [{Pid, Ref, follow}|Waiters]},
  891. Rev = {{Pid,K}, []},
  892. ets:insert(?TAB, [Obj, Rev]),
  893. Msg = {gproc, unreg, Ref, K},
  894. if node(Pid) == node() ->
  895. Pid ! Msg,
  896. {reply, Ref, [{insert, [Obj, Rev]}], S};
  897. true ->
  898. {reply, Ref, [{insert, [Obj, Rev]},
  899. {notify, [{Pid, Msg}]}]}
  900. end.