gproc.erl 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995
  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@erlang-consulting.com>
  17. %%
  18. %% @doc Extended process registry
  19. %% This module implements an extended process registry
  20. %%
  21. %% For a detailed description, see
  22. %% <a href="erlang07-wiger.pdf">erlang07-wiger.pdf</a>.
  23. %%
  24. %% <h2>Tuning Gproc performance</h2>
  25. %%
  26. %% Gproc relies on a central server and an ordered-set ets table.
  27. %% Effort is made to perform as much work as possible in the client without
  28. %% sacrificing consistency. A few things can be tuned by setting the following
  29. %% application environment variables in the top application of `gproc'
  30. %% (usually `gproc'):
  31. %%
  32. %% * `{ets_options, list()}' - Currently, the options `{write_concurrency, F}'
  33. %% and `{read_concurrency, F}' are allowed. The default is
  34. %% `[{write_concurrency, true}, {read_concurrency, true}]'
  35. %% * `{server_options, list()}' - These will be passed as spawn options when
  36. %% starting the `gproc' and `gproc_dist' servers. Default is `[]'. It is
  37. %% likely that `{priority, high | max}' and/or increasing `min_heap_size'
  38. %% will improve performance.
  39. %%
  40. %% @end
  41. %% @type type() = n | p | c | a. n = name; p = property; c = counter;
  42. %% a = aggregate_counter
  43. %% @type scope() = l | g. l = local registration; g = global registration
  44. %%
  45. %% @type reg_id() = {type(), scope(), any()}.
  46. %% @type unique_id() = {n | a, scope(), any()}.
  47. %%
  48. %% @type sel_scope() = scope | all | global | local.
  49. %% @type sel_type() = type() | names | props | counters | aggr_counters.
  50. %% @type context() = {scope(), type()} | type(). {'all','all'} is the default
  51. %%
  52. %% @type headpat() = {keypat(),pidpat(),ValPat}.
  53. %% @type keypat() = {sel_type() | sel_var(),
  54. %% l | g | sel_var(),
  55. %% any()}.
  56. %% @type pidpat() = pid() | sel_var().
  57. %% sel_var() = DollarVar | '_'.
  58. %% @type sel_pattern() = [{headpat(), Guards, Prod}].
  59. %% @type key() = {type(), scope(), any()}.
  60. -module(gproc).
  61. -behaviour(gen_server).
  62. -export([start_link/0,
  63. reg/1, reg/2, unreg/1,
  64. reg_shared/1, reg_shared/2, unreg_shared/1,
  65. mreg/3,
  66. munreg/3,
  67. set_value/2,
  68. get_value/1, get_value/2,
  69. where/1,
  70. await/1, await/2,
  71. nb_wait/1,
  72. cancel_wait/2,
  73. monitor/1,
  74. demonitor/2,
  75. lookup_pid/1,
  76. lookup_pids/1,
  77. lookup_value/1,
  78. lookup_values/1,
  79. update_counter/2,
  80. reset_counter/1,
  81. update_shared_counter/2,
  82. give_away/2,
  83. goodbye/0,
  84. send/2,
  85. info/1, info/2,
  86. i/0,
  87. select/1, select/2, select/3,
  88. select_count/1, select_count/2,
  89. first/1,
  90. next/2,
  91. prev/2,
  92. last/1,
  93. table/0, table/1, table/2]).
  94. %% Environment handling
  95. -export([get_env/3, get_env/4,
  96. get_set_env/3, get_set_env/4,
  97. set_env/5]).
  98. %% Convenience functions
  99. -export([add_local_name/1,
  100. add_global_name/1,
  101. add_local_property/2,
  102. add_global_property/2,
  103. add_local_counter/2,
  104. add_global_counter/2,
  105. add_local_aggr_counter/1,
  106. add_global_aggr_counter/1,
  107. add_shared_local_counter/2,
  108. lookup_local_name/1,
  109. lookup_global_name/1,
  110. lookup_local_properties/1,
  111. lookup_global_properties/1,
  112. lookup_local_counters/1,
  113. lookup_global_counters/1,
  114. lookup_local_aggr_counter/1,
  115. lookup_global_aggr_counter/1]).
  116. %% Callbacks for behaviour support
  117. -export([whereis_name/1,
  118. register_name/2,
  119. unregister_name/1]).
  120. -export([default/1]).
  121. %%% internal exports
  122. -export([init/1,
  123. handle_cast/2,
  124. handle_call/3,
  125. handle_info/2,
  126. code_change/3,
  127. terminate/2]).
  128. %% this shouldn't be necessary
  129. -export([audit_process/1]).
  130. -include("gproc.hrl").
  131. -include_lib("eunit/include/eunit.hrl").
  132. -define(SERVER, ?MODULE).
  133. %%-define(l, l(?LINE)). % when activated, calls a traceable empty function
  134. -define(l, ignore).
  135. -define(CHK_DIST,
  136. case whereis(gproc_dist) of
  137. undefined ->
  138. erlang:error(local_only);
  139. _ ->
  140. ok
  141. end).
  142. -record(state, {}).
  143. %% @spec () -> {ok, pid()}
  144. %%
  145. %% @doc Starts the gproc server.
  146. %%
  147. %% This function is intended to be called from gproc_sup, as part of
  148. %% starting the gproc application.
  149. %% @end
  150. start_link() ->
  151. _ = create_tabs(),
  152. SpawnOpts = gproc_lib:valid_opts(server_options, []),
  153. gen_server:start_link({local, ?SERVER}, ?MODULE, [],
  154. [{spawn_opt, SpawnOpts}]).
  155. %% spec(Name::any()) -> true
  156. %%
  157. %% @doc Registers a local (unique) name. @equiv reg({n,l,Name})
  158. %% @end
  159. %%
  160. add_local_name(Name) -> reg({n,l,Name}, undefined).
  161. %% spec(Name::any()) -> true
  162. %%
  163. %% @doc Registers a global (unique) name. @equiv reg({n,g,Name})
  164. %% @end
  165. %%
  166. add_global_name(Name) -> reg({n,g,Name}, undefined).
  167. %% spec(Name::any(), Value::any()) -> true
  168. %%
  169. %% @doc Registers a local (non-unique) property. @equiv reg({p,l,Name},Value)
  170. %% @end
  171. %%
  172. add_local_property(Name , Value) -> reg({p,l,Name}, Value).
  173. %% spec(Name::any(), Value::any()) -> true
  174. %%
  175. %% @doc Registers a global (non-unique) property. @equiv reg({p,g,Name},Value)
  176. %% @end
  177. %%
  178. add_global_property(Name, Value) -> reg({p,g,Name}, Value).
  179. %% spec(Name::any(), Initial::integer()) -> true
  180. %%
  181. %% @doc Registers a local (non-unique) counter. @equiv reg({c,l,Name},Value)
  182. %% @end
  183. %%
  184. add_local_counter(Name, Initial) when is_integer(Initial) ->
  185. reg({c,l,Name}, Initial).
  186. %% spec(Name::any(), Initial::integer()) -> true
  187. %%
  188. %% @doc Registers a local shared (unique) counter.
  189. %% @equiv reg_shared({c,l,Name},Value)
  190. %% @end
  191. %%
  192. add_shared_local_counter(Name, Initial) when is_integer(Initial) ->
  193. reg_shared({c,l,Name}, Initial).
  194. %% spec(Name::any(), Initial::integer()) -> true
  195. %%
  196. %% @doc Registers a global (non-unique) counter. @equiv reg({c,g,Name},Value)
  197. %% @end
  198. %%
  199. add_global_counter(Name, Initial) when is_integer(Initial) ->
  200. reg({c,g,Name}, Initial).
  201. %% spec(Name::any()) -> true
  202. %%
  203. %% @doc Registers a local (unique) aggregated counter.
  204. %% @equiv reg({a,l,Name})
  205. %% @end
  206. %%
  207. add_local_aggr_counter(Name) -> reg({a,l,Name}).
  208. %% spec(Name::any()) -> true
  209. %%
  210. %% @doc Registers a global (unique) aggregated counter.
  211. %% @equiv reg({a,g,Name})
  212. %% @end
  213. %%
  214. add_global_aggr_counter(Name) -> reg({a,g,Name}).
  215. %% @spec (Name::any()) -> pid()
  216. %%
  217. %% @doc Lookup a local unique name. Fails if there is no such name.
  218. %% @equiv where({n,l,Name})
  219. %% @end
  220. %%
  221. lookup_local_name(Name) -> where({n,l,Name}).
  222. %% @spec (Name::any()) -> pid()
  223. %%
  224. %% @doc Lookup a global unique name. Fails if there is no such name.
  225. %% @equiv where({n,g,Name})
  226. %% @end
  227. %%
  228. lookup_global_name(Name) -> where({n,g,Name}).
  229. %% @spec (Name::any()) -> integer()
  230. %%
  231. %% @doc Lookup a local (unique) aggregated counter and returns its value.
  232. %% Fails if there is no such object.
  233. %% @equiv where({a,l,Name})
  234. %% @end
  235. %%
  236. lookup_local_aggr_counter(Name) -> lookup_value({a,l,Name}).
  237. %% @spec (Name::any()) -> integer()
  238. %%
  239. %% @doc Lookup a global (unique) aggregated counter and returns its value.
  240. %% Fails if there is no such object.
  241. %% @equiv where({a,g,Name})
  242. %% @end
  243. %%
  244. lookup_global_aggr_counter(Name) -> lookup_value({a,g,Name}).
  245. %% @spec (Property::any()) -> [{pid(), Value}]
  246. %%
  247. %% @doc Look up all local (non-unique) instances of a given Property.
  248. %% Returns a list of {Pid, Value} tuples for all matching objects.
  249. %% @equiv lookup_values({p, l, Property})
  250. %% @end
  251. %%
  252. lookup_local_properties(P) -> lookup_values({p,l,P}).
  253. %% @spec (Property::any()) -> [{pid(), Value}]
  254. %%
  255. %% @doc Look up all global (non-unique) instances of a given Property.
  256. %% Returns a list of {Pid, Value} tuples for all matching objects.
  257. %% @equiv lookup_values({p, g, Property})
  258. %% @end
  259. %%
  260. lookup_global_properties(P) -> lookup_values({p,g,P}).
  261. %% @spec (Counter::any()) -> [{pid(), Value::integer()}]
  262. %%
  263. %% @doc Look up all local (non-unique) instances of a given Counter.
  264. %% Returns a list of {Pid, Value} tuples for all matching objects.
  265. %% @equiv lookup_values({c, l, Counter})
  266. %% @end
  267. %%
  268. lookup_local_counters(P) -> lookup_values({c,l,P}).
  269. %% @spec (Counter::any()) -> [{pid(), Value::integer()}]
  270. %%
  271. %% @doc Look up all global (non-unique) instances of a given Counter.
  272. %% Returns a list of {Pid, Value} tuples for all matching objects.
  273. %% @equiv lookup_values({c, g, Counter})
  274. %% @end
  275. %%
  276. lookup_global_counters(P) -> lookup_values({c,g,P}).
  277. %% @spec get_env(Scope::scope(), App::atom(), Key::atom()) -> term()
  278. %% @equiv get_env(Scope, App, Key, [app_env])
  279. get_env(Scope, App, Key) ->
  280. get_env(Scope, App, Key, [app_env]).
  281. %% @spec (Scope::scope(), App::atom(), Key::atom(), Strategy) -> term()
  282. %% Strategy = [Alternative]
  283. %% Alternative = app_env
  284. %% | os_env
  285. %% | inherit | {inherit, pid()} | {inherit, unique_id()}
  286. %% | init_arg
  287. %% | {mnesia, ActivityType, Oid, Pos}
  288. %% | {default, term()}
  289. %% | error
  290. %% @doc Read an environment value, potentially cached as a `gproc_env' property.
  291. %%
  292. %% This function first tries to read the value of a cached property,
  293. %% `{p, Scope, {gproc_env, App, Key}}'. If this fails, it will try the provided
  294. %% alternative strategy. `Strategy' is a list of alternatives, tried in order.
  295. %% Each alternative can be one of:
  296. %%
  297. %% * `app_env' - try `application:get_env(App, Key)'
  298. %% * `os_env' - try `os:getenv(ENV)', where `ENV' is `Key' converted into an
  299. %% uppercase string
  300. %% * `{os_env, ENV}' - try `os:getenv(ENV)'
  301. %% * `inherit' - inherit the cached value, if any, held by the parent process.
  302. %% * `{inherit, Pid}' - inherit the cached value, if any, held by `Pid'.
  303. %% * `{inherit, Id}' - inherit the cached value, if any, held by the process
  304. %% registered in `gproc' as `Id'.
  305. %% * `init_arg' - try `init:get_argument(Key)'; expects a single value, if any.
  306. %% * `{mnesia, ActivityType, Oid, Pos}' - try
  307. %% `mnesia:activity(ActivityType, fun() -> mnesia:read(Oid) end)'; retrieve
  308. %% the value in position `Pos' if object found.
  309. %% * `{default, Value}' - set a default value to return once alternatives have
  310. %% been exhausted; if not set, `undefined' will be returned.
  311. %% * `error' - raise an exception, `erlang:error(gproc_env, [App, Key, Scope])'.
  312. %%
  313. %% While any alternative can occur more than once, the only one that might make
  314. %% sense to use multiple times is `{default, Value}'.
  315. %%
  316. %% The return value will be one of:
  317. %%
  318. %% * The value of the first matching alternative, or `error' eception,
  319. %% whichever comes first
  320. %% * The last instance of `{default, Value}', or `undefined', if there is no
  321. %% matching alternative, default or `error' entry in the list.
  322. %%
  323. %% The `error' option can be used to assert that a value has been previously
  324. %% cached. Alternatively, it can be used to assert that a value is either cached
  325. %% or at least defined somewhere,
  326. %% e.g. `get_env(l, mnesia, dir, [app_env, error])'.
  327. %% @end
  328. get_env(Scope, App, Key, Strategy)
  329. when Scope==l, is_atom(App), is_atom(Key);
  330. Scope==g, is_atom(App), is_atom(Key) ->
  331. do_get_env(Scope, App, Key, Strategy, false).
  332. %% @spec get_set_env(Scope::scope(), App::atom(), Key::atom()) -> term()
  333. %% @equiv get_set_env(Scope, App, Key, [app_env])
  334. get_set_env(Scope, App, Key) ->
  335. get_set_env(Scope, App, Key, [app_env]).
  336. %% @spec get_set_env(Scope::scope(), App::atom(), Key::atom(), Strategy) ->
  337. %% Value
  338. %% @doc Fetch and cache an environment value, if not already cached.
  339. %%
  340. %% This function does the same thing as {@link get_env/4}, but also updates the
  341. %% cache. Note that the cache will be updated even if the result of the lookup
  342. %% is `undefined'.
  343. %%
  344. %% @see get_env/4.
  345. %% @end
  346. %%
  347. get_set_env(Scope, App, Key, Strategy)
  348. when Scope==l, is_atom(App), is_atom(Key);
  349. Scope==g, is_atom(App), is_atom(Key) ->
  350. do_get_env(Scope, App, Key, Strategy, true).
  351. do_get_env(Context, App, Key, Alternatives, Set) ->
  352. case lookup_env(Context, App, Key, self()) of
  353. undefined ->
  354. check_alternatives(Alternatives, Context, App, Key, undefined, Set);
  355. {ok, Value} ->
  356. Value
  357. end.
  358. %% @spec set_env(Scope::scope(), App::atom(),
  359. %% Key::atom(), Value::term(), Strategy) -> Value
  360. %% Strategy = [Alternative]
  361. %% Alternative = app_env | os_env | {os_env, VAR}
  362. %% | {mnesia, ActivityType, Oid, Pos}
  363. %%
  364. %% @doc Updates the cached value as well as underlying environment.
  365. %%
  366. %% This function should be exercised with caution, as it affects the larger
  367. %% environment outside gproc. This function modifies the cached value, and then
  368. %% proceeds to update the underlying environment (OS environment variable or
  369. %% application environment variable).
  370. %%
  371. %% When the `mnesia' alternative is used, gproc will try to update any existing
  372. %% object, changing only the `Pos' position. If no such object exists, it will
  373. %% create a new object, setting any other attributes (except `Pos' and the key)
  374. %% to `undefined'.
  375. %% @end
  376. %%
  377. set_env(Scope, App, Key, Value, Strategy)
  378. when Scope==l, is_atom(App), is_atom(Key);
  379. Scope==g, is_atom(App), is_atom(Key) ->
  380. case is_valid_set_strategy(Strategy, Value) of
  381. true ->
  382. update_cached_env(Scope, App, Key, Value),
  383. set_strategy(Strategy, App, Key, Value);
  384. false ->
  385. erlang:error(badarg)
  386. end.
  387. check_alternatives([{default, Val}|Alts], Scope, App, Key, _, Set) ->
  388. check_alternatives(Alts, Scope, App, Key, Val, Set);
  389. check_alternatives([H|T], Scope, App, Key, Def, Set) ->
  390. case try_alternative(H, App, Key, Scope) of
  391. undefined ->
  392. check_alternatives(T, Scope, App, Key, Def, Set);
  393. {ok, Value} ->
  394. if Set ->
  395. cache_env(Scope, App, Key, Value),
  396. Value;
  397. true ->
  398. Value
  399. end
  400. end;
  401. check_alternatives([], Scope, App, Key, Def, Set) ->
  402. if Set ->
  403. cache_env(Scope, App, Key, Def);
  404. true ->
  405. ok
  406. end,
  407. Def.
  408. try_alternative(error, App, Key, Scope) ->
  409. erlang:error(gproc_env, [App, Key, Scope]);
  410. try_alternative(inherit, App, Key, Scope) ->
  411. case get('$ancestors') of
  412. [P|_] ->
  413. lookup_env(Scope, App, Key, P);
  414. _ ->
  415. undefined
  416. end;
  417. try_alternative({inherit, P}, App, Key, Scope) when is_pid(P) ->
  418. lookup_env(Scope, App, Key, P);
  419. try_alternative({inherit, P}, App, Key, Scope) ->
  420. case where(P) of
  421. undefined -> undefined;
  422. Pid when is_pid(Pid) ->
  423. lookup_env(Scope, App, Key, Pid)
  424. end;
  425. try_alternative(app_env, App, Key, _Scope) ->
  426. case application:get_env(App, Key) of
  427. undefined -> undefined;
  428. {ok, undefined} -> undefined;
  429. {ok, Value} -> {ok, Value}
  430. end;
  431. try_alternative(os_env, _App, Key, _) ->
  432. case os:getenv(os_env_key(Key)) of
  433. false -> undefined;
  434. Val -> {ok, Val}
  435. end;
  436. try_alternative({os_env, Key}, _, _, _) ->
  437. case os:getenv(Key) of
  438. false -> undefined;
  439. Val -> {ok, Val}
  440. end;
  441. try_alternative(init_arg, _, Key, _) ->
  442. case init:get_argument(Key) of
  443. {ok, [[Value]]} ->
  444. {ok, Value};
  445. error ->
  446. undefined
  447. end;
  448. try_alternative({mnesia,Type,Key,Pos}, _, _, _) ->
  449. case mnesia:activity(Type, fun() -> mnesia:read(Key) end) of
  450. [] -> undefined;
  451. [Found] ->
  452. {ok, element(Pos, Found)}
  453. end.
  454. os_env_key(Key) ->
  455. string:to_upper(atom_to_list(Key)).
  456. lookup_env(Scope, App, Key, P) ->
  457. case ets:lookup(?TAB, {{p, Scope, {gproc_env, App, Key}}, P}) of
  458. [] ->
  459. undefined;
  460. [{_, _, Value}] ->
  461. {ok, Value}
  462. end.
  463. cache_env(Scope, App, Key, Value) ->
  464. reg({p, Scope, {gproc_env, App, Key}}, Value).
  465. update_cached_env(Scope, App, Key, Value) ->
  466. case lookup_env(Scope, App, Key, self()) of
  467. undefined ->
  468. cache_env(Scope, App, Key, Value);
  469. {ok, _} ->
  470. set_value({p, Scope, {gproc_env, App, Key}}, Value)
  471. end.
  472. is_valid_set_strategy([os_env|T], Value) ->
  473. is_string(Value) andalso is_valid_set_strategy(T, Value);
  474. is_valid_set_strategy([{os_env, _}|T], Value) ->
  475. is_string(Value) andalso is_valid_set_strategy(T, Value);
  476. is_valid_set_strategy([app_env|T], Value) ->
  477. is_valid_set_strategy(T, Value);
  478. is_valid_set_strategy([{mnesia,_Type,_Oid,_Pos}|T], Value) ->
  479. is_valid_set_strategy(T, Value);
  480. is_valid_set_strategy([], _) ->
  481. true;
  482. is_valid_set_strategy(_, _) ->
  483. false.
  484. set_strategy([H|T], App, Key, Value) ->
  485. case H of
  486. app_env ->
  487. application:set_env(App, Key, Value);
  488. os_env ->
  489. os:putenv(os_env_key(Key), Value);
  490. {os_env, ENV} ->
  491. os:putenv(ENV, Value);
  492. {mnesia,Type,Oid,Pos} ->
  493. mnesia:activity(
  494. Type,
  495. fun() ->
  496. Rec = case mnesia:read(Oid) of
  497. [] ->
  498. {Tab,K} = Oid,
  499. Tag = mnesia:table_info(Tab, record_name),
  500. Attrs = mnesia:table_info(Tab, attributes),
  501. list_to_tuple(
  502. [Tag,K |
  503. [undefined || _ <- tl(Attrs)]]);
  504. [Old] ->
  505. Old
  506. end,
  507. mnesia:write(setelement(Pos, Rec, Value))
  508. end)
  509. end,
  510. set_strategy(T, App, Key, Value);
  511. set_strategy([], _, _, Value) ->
  512. Value.
  513. is_string(S) ->
  514. try begin _ = iolist_to_binary(S),
  515. true
  516. end
  517. catch
  518. error:_ ->
  519. false
  520. end.
  521. %% @spec reg(Key::key()) -> true
  522. %%
  523. %% @doc
  524. %% @equiv reg(Key, default(Key))
  525. %% @end
  526. reg(Key) ->
  527. reg(Key, default(Key)).
  528. default({T,_,_}) when T==c -> 0;
  529. default(_) -> undefined.
  530. %% @spec await(Key::key()) -> {pid(),Value}
  531. %% @equiv await(Key,infinity)
  532. %%
  533. await(Key) ->
  534. await(Key, infinity).
  535. %% @spec await(Key::key(), Timeout) -> {pid(),Value}
  536. %% Timeout = integer() | infinity
  537. %%
  538. %% @doc Wait for a local name to be registered.
  539. %% The function raises an exception if the timeout expires. Timeout must be
  540. %% either an interger &gt; 0 or 'infinity'.
  541. %% A small optimization: we first perform a lookup, to see if the name
  542. %% is already registered. This way, the cost of the operation will be
  543. %% roughly the same as of where/1 in the case where the name is already
  544. %% registered (the difference: await/2 also returns the value).
  545. %% @end
  546. %%
  547. await({n,g,_} = Key, Timeout) ->
  548. ?CHK_DIST,
  549. request_wait(Key, Timeout);
  550. await({n,l,_} = Key, Timeout) ->
  551. case ets:lookup(?TAB, {Key, n}) of
  552. [{_, Pid, Value}] ->
  553. {Pid, Value};
  554. _ ->
  555. request_wait(Key, Timeout)
  556. end;
  557. await(K, T) ->
  558. erlang:error(badarg, [K, T]).
  559. request_wait({n,C,_} = Key, Timeout) when C==l; C==g ->
  560. TRef = case Timeout of
  561. infinity -> no_timer;
  562. T when is_integer(T), T > 0 ->
  563. erlang:start_timer(T, self(), gproc_timeout);
  564. _ ->
  565. erlang:error(badarg, [Key, Timeout])
  566. end,
  567. WRef = case {call({await,Key,self()}, C), C} of
  568. {{R, {Kg,Pg,Vg}}, g} ->
  569. self() ! {gproc, R, registered, {Kg,Pg,Vg}},
  570. R;
  571. {R,_} ->
  572. R
  573. end,
  574. receive
  575. {gproc, WRef, registered, {_K, Pid, V}} ->
  576. _ = case TRef of
  577. no_timer -> ignore;
  578. _ -> erlang:cancel_timer(TRef)
  579. end,
  580. {Pid, V};
  581. {timeout, TRef, gproc_timeout} ->
  582. cancel_wait(Key, WRef),
  583. erlang:error(timeout, [Key, Timeout])
  584. end.
  585. %% @spec nb_wait(Key::key()) -> Ref
  586. %%
  587. %% @doc Wait for a local name to be registered.
  588. %% The caller can expect to receive a message,
  589. %% {gproc, Ref, registered, {Key, Pid, Value}}, once the name is registered.
  590. %% @end
  591. %%
  592. nb_wait({n,g,_} = Key) ->
  593. ?CHK_DIST,
  594. call({await, Key, self()}, g);
  595. nb_wait({n,l,_} = Key) ->
  596. call({await, Key, self()}, l);
  597. nb_wait(Key) ->
  598. erlang:error(badarg, [Key]).
  599. cancel_wait({_,g,_} = Key, Ref) ->
  600. ?CHK_DIST,
  601. cast({cancel_wait, self(), Key, Ref}, g),
  602. ok;
  603. cancel_wait({_,l,_} = Key, Ref) ->
  604. cast({cancel_wait, self(), Key, Ref}, l),
  605. ok.
  606. %% @spec monitor(key()) -> reference()
  607. %%
  608. %% @doc monitor a registered name
  609. %% This function works much like erlang:monitor(process, Pid), but monitors
  610. %% a unique name registered via gproc. A message, `{gproc, unreg, Ref, Key}'
  611. %% will be sent to the requesting process, if the name is unregistered or
  612. %% the registered process dies.
  613. %%
  614. %% If the name is not yet registered, the same message is sent immediately.
  615. %% @end
  616. monitor({T,g,_} = Key) when T==n; T==a ->
  617. ?CHK_DIST,
  618. call({monitor, Key}, g);
  619. monitor({T,l,_} = Key) when T==n; T==a ->
  620. call({monitor, Key}, l);
  621. monitor(Key) ->
  622. erlang:error(badarg, [Key]).
  623. %% @spec demonitor(key(), reference()) -> ok
  624. %%
  625. %% @doc Remove a monitor on a registered name
  626. %% This function is the reverse of monitor/1. It removes a monitor previously
  627. %% set on a unique name. This function always succeeds given legal input.
  628. %% @end
  629. demonitor({T,g,_} = Key, Ref) when T==n; T==a ->
  630. ?CHK_DIST,
  631. call({demonitor, Key, Ref}, g);
  632. demonitor({T,l,_} = Key, Ref) when T==n; T==a ->
  633. call({demonitor, Key, Ref}, l);
  634. demonitor(Key, Ref) ->
  635. erlang:error(badarg, [Key, Ref]).
  636. %% @spec reg(Key::key(), Value) -> true
  637. %%
  638. %% @doc Register a name or property for the current process
  639. %%
  640. %%
  641. reg({_,g,_} = Key, Value) ->
  642. %% anything global
  643. ?CHK_DIST,
  644. gproc_dist:reg(Key, Value);
  645. reg({p,l,_} = Key, Value) ->
  646. local_reg(Key, Value);
  647. reg({a,l,_} = Key, undefined) ->
  648. call({reg, Key, undefined});
  649. reg({c,l,_} = Key, Value) when is_integer(Value) ->
  650. call({reg, Key, Value});
  651. reg({n,l,_} = Key, Value) ->
  652. call({reg, Key, Value});
  653. reg(_, _) ->
  654. erlang:error(badarg).
  655. %% @spec reg_shared(Key::key()) -> true
  656. %%
  657. %% @doc Register a resource, but don't tie it to a particular process.
  658. %%
  659. %% `reg_shared({c,l,C}) -> reg_shared({c,l,C}, 0).'
  660. %% `reg_shared({a,l,A}) -> reg_shared({a,l,A}, undefined).'
  661. %% @end
  662. reg_shared({c,_,_} = Key) ->
  663. reg_shared(Key, 0);
  664. reg_shared({a,_,_} = Key) ->
  665. reg_shared(Key, undefined).
  666. %% @spec reg_shared(Key::key(), Value) -> true
  667. %%
  668. %% @doc Register a resource, but don't tie it to a particular process.
  669. %%
  670. %% Shared resources are all unique. They remain until explicitly unregistered
  671. %% (using {@link unreg_shared/1}). The types of shared resources currently
  672. %% supported are `counter' and `aggregated counter'. In listings and query
  673. %% results, shared resources appear as other similar resources, except that
  674. %% `Pid == shared'. To wit, update_counter({c,l,myCounter}, 1, shared) would
  675. %% increment the shared counter `myCounter' with 1, provided it exists.
  676. %%
  677. %% A shared aggregated counter will track updates in exactly the same way as
  678. %% an aggregated counter which is owned by a process.
  679. %% @end
  680. %%
  681. reg_shared({_,g,_} = Key, Value) ->
  682. %% anything global
  683. ?CHK_DIST,
  684. gproc_dist:reg_shared(Key, Value);
  685. reg_shared({a,l,_} = Key, undefined) ->
  686. call({reg_shared, Key, undefined});
  687. reg_shared({c,l,_} = Key, Value) when is_integer(Value) ->
  688. call({reg_shared, Key, Value});
  689. reg_shared(_, _) ->
  690. erlang:error(badarg).
  691. %% @spec mreg(type(), scope(), [{Key::any(), Value::any()}]) -> true
  692. %%
  693. %% @doc Register multiple {Key,Value} pairs of a given type and scope.
  694. %%
  695. %% This function is more efficient than calling {@link reg/2} repeatedly.
  696. %% It is also atomic in regard to unique names; either all names are registered
  697. %% or none are.
  698. %% @end
  699. mreg(T, g, KVL) ->
  700. ?CHK_DIST,
  701. gproc_dist:mreg(T, KVL);
  702. mreg(T, l, KVL) when T==a; T==n ->
  703. if is_list(KVL) ->
  704. call({mreg, T, l, KVL});
  705. true ->
  706. erlang:error(badarg)
  707. end;
  708. mreg(p, l, KVL) ->
  709. local_mreg(p, KVL);
  710. mreg(_, _, _) ->
  711. erlang:error(badarg).
  712. %% @spec munreg(type(), scope(), [Key::any()]) -> true
  713. %%
  714. %% @doc Unregister multiple Key items of a given type and scope.
  715. %%
  716. %% This function is usually more efficient than calling {@link unreg/1}
  717. %% repeatedly.
  718. %% @end
  719. munreg(T, g, L) ->
  720. ?CHK_DIST,
  721. gproc_dist:munreg(T, existing(T,g,L));
  722. munreg(T, l, L) when T==a; T==n ->
  723. if is_list(L) ->
  724. call({munreg, T, l, existing(T,l,L)});
  725. true ->
  726. erlang:error(badarg)
  727. end;
  728. munreg(p, l, L) ->
  729. local_munreg(p, existing(p,l,L));
  730. munreg(_, _, _) ->
  731. erlang:error(badarg).
  732. existing(T,Scope,L) ->
  733. Keys = if T==p; T==c ->
  734. [{{T,Scope,K}, self()} || K <- L];
  735. T==a; T==n ->
  736. [{{T,Scope,K}, T} || K <- L]
  737. end,
  738. _ = [case ets:member(?TAB, K) of
  739. false -> erlang:error(badarg);
  740. true -> true
  741. end || K <- Keys],
  742. L.
  743. %% @spec (Key:: key()) -> true
  744. %%
  745. %% @doc Unregister a name or property.
  746. %% @end
  747. unreg(Key) ->
  748. case Key of
  749. {_, g, _} ->
  750. ?CHK_DIST,
  751. gproc_dist:unreg(Key);
  752. {T, l, _} when T == n;
  753. T == a -> call({unreg, Key});
  754. {_, l, _} ->
  755. case ets:member(?TAB, {Key,self()}) of
  756. true ->
  757. _ = gproc_lib:remove_reg(Key, self()),
  758. true;
  759. false ->
  760. erlang:error(badarg)
  761. end
  762. end.
  763. %% @spec (Key:: key()) -> true
  764. %%
  765. %% @doc Unregister a shared resource.
  766. %% @end
  767. unreg_shared(Key) ->
  768. case Key of
  769. {_, g, _} ->
  770. ?CHK_DIST,
  771. gproc_dist:unreg_shared(Key);
  772. {T, l, _} when T == c;
  773. T == a -> call({unreg_shared, Key});
  774. _ ->
  775. erlang:error(badarg)
  776. end.
  777. %% @spec (key(), pid()) -> yes | no
  778. %%
  779. %% @doc Behaviour support callback
  780. %% @end
  781. register_name({n,_,_} = Name, Pid) when Pid == self() ->
  782. try reg(Name), yes
  783. catch
  784. error:_ ->
  785. no
  786. end.
  787. %% @equiv unreg/1
  788. unregister_name(Key) ->
  789. unreg(Key).
  790. %% @spec (Continuation ::term()) -> {[Match],Continuation} | '$end_of_table'
  791. %% @doc
  792. %% see http://www.erlang.org/doc/man/ets.html#select-1
  793. %% @end
  794. select({?TAB, _, _, _, _, _, _, _} = Continuation) ->
  795. ets:select(Continuation);
  796. %% @spec (select_pattern()) -> list(sel_object())
  797. %% @doc
  798. %% @equiv select(all, Pat)
  799. %% @end
  800. select(Pat) ->
  801. select(all, Pat).
  802. %% @spec (Context::context(), Pat::sel_pattern()) -> [{Key, Pid, Value}]
  803. %%
  804. %% @doc Perform a select operation on the process registry.
  805. %%
  806. %% The physical representation in the registry may differ from the above,
  807. %% but the select patterns are transformed appropriately.
  808. %% @end
  809. select(Context, Pat) ->
  810. ets:select(?TAB, pattern(Pat, Context)).
  811. %% @spec (Context::context(), Pat::sel_patten(), Limit::integer()) ->
  812. %% {[Match],Continuation} | '$end_of_table'
  813. %% @doc Like {@link select/2} but returns Limit objects at a time.
  814. %%
  815. %% See [http://www.erlang.org/doc/man/ets.html#select-3].
  816. %% @end
  817. select(Context, Pat, Limit) ->
  818. ets:select(?TAB, pattern(Pat, Context), Limit).
  819. %% @spec (select_pattern()) -> list(sel_object())
  820. %% @doc
  821. %% @equiv select_count(all, Pat)
  822. %% @end
  823. select_count(Pat) ->
  824. select_count(all, Pat).
  825. %% @spec (Context::context(), Pat::sel_pattern()) -> [{Key, Pid, Value}]
  826. %%
  827. %% @doc Perform a select_count operation on the process registry.
  828. %%
  829. %% The physical representation in the registry may differ from the above,
  830. %% but the select patterns are transformed appropriately.
  831. %% @end
  832. select_count(Context, Pat) ->
  833. ets: select_count(?TAB, pattern(Pat, Context)).
  834. %%% Local properties can be registered in the local process, since
  835. %%% no other process can interfere.
  836. %%%
  837. local_reg(Key, Value) ->
  838. case gproc_lib:insert_reg(Key, Value, self(), l) of
  839. false -> erlang:error(badarg);
  840. true -> monitor_me()
  841. end.
  842. local_mreg(_, []) -> true;
  843. local_mreg(T, [_|_] = KVL) ->
  844. case gproc_lib:insert_many(T, l, KVL, self()) of
  845. false -> erlang:error(badarg);
  846. {true,_} -> monitor_me()
  847. end.
  848. local_munreg(T, L) when T==p; T==c ->
  849. _ = [gproc_lib:remove_reg({T,l,K}, self()) || K <- L],
  850. true.
  851. %% @spec (Key :: key(), Value) -> true
  852. %% @doc Sets the value of the registeration entry given by Key
  853. %%
  854. %% Key is assumed to exist and belong to the calling process.
  855. %% If it doesn't, this function will exit.
  856. %%
  857. %% Value can be any term, unless the object is a counter, in which case
  858. %% it must be an integer.
  859. %% @end
  860. %%
  861. set_value({_,g,_} = Key, Value) ->
  862. ?CHK_DIST,
  863. gproc_dist:set_value(Key, Value);
  864. set_value({a,l,_} = Key, Value) when is_integer(Value) ->
  865. call({set, Key, Value});
  866. set_value({n,l,_} = Key, Value) ->
  867. %% we cannot do this locally, since we have to check that the object
  868. %% exists first - not an atomic update.
  869. call({set, Key, Value});
  870. set_value({p,l,_} = Key, Value) ->
  871. %% we _can_ to this locally, since there is no race condition - no
  872. %% other process can update our properties.
  873. case gproc_lib:do_set_value(Key, Value, self()) of
  874. true -> true;
  875. false ->
  876. erlang:error(badarg)
  877. end;
  878. set_value({c,l,_} = Key, Value) when is_integer(Value) ->
  879. gproc_lib:do_set_counter_value(Key, Value, self());
  880. set_value(_, _) ->
  881. erlang:error(badarg).
  882. %% @spec (Key) -> Value
  883. %% @doc Reads the value stored with a key registered to the current process.
  884. %%
  885. %% If no such key is registered to the current process, this function exits.
  886. %% @end
  887. get_value(Key) ->
  888. get_value(Key, self()).
  889. %% @spec (Key, Pid) -> Value
  890. %% @doc Reads the value stored with a key registered to the process Pid.
  891. %%
  892. %% If `Pid == shared', the value of a shared key (see {@link reg_shared/1})
  893. %% will be read.
  894. %% @end
  895. %%
  896. get_value({T,_,_} = Key, Pid) when is_pid(Pid) ->
  897. if T==n orelse T==a ->
  898. case ets:lookup(?TAB, {Key, T}) of
  899. [{_, P, Value}] when P == Pid -> Value;
  900. _ -> erlang:error(badarg)
  901. end;
  902. true ->
  903. ets:lookup_element(?TAB, {Key, Pid}, 3)
  904. end;
  905. get_value({T,_,_} = K, shared) when T==c; T==a ->
  906. Key = case T of
  907. c -> {K, shared};
  908. a -> {K, a}
  909. end,
  910. case ets:lookup(?TAB, Key) of
  911. [{_, shared, Value}] -> Value;
  912. _ -> erlang:error(badarg)
  913. end;
  914. get_value(_, _) ->
  915. erlang:error(badarg).
  916. %% @spec (Key) -> Pid
  917. %% @doc Lookup the Pid stored with a key.
  918. %%
  919. lookup_pid({_T,_,_} = Key) ->
  920. case where(Key) of
  921. undefined -> erlang:error(badarg);
  922. P -> P
  923. end.
  924. %% @spec (Key) -> Value
  925. %% @doc Lookup the value stored with a key.
  926. %%
  927. lookup_value({T,_,_} = Key) ->
  928. if T==n orelse T==a ->
  929. ets:lookup_element(?TAB, {Key,T}, 3);
  930. true ->
  931. erlang:error(badarg)
  932. end.
  933. %% @spec (Key::key()) -> pid()
  934. %%
  935. %% @doc Returns the pid registered as Key
  936. %%
  937. %% The type of registration entry must be either name or aggregated counter.
  938. %% Otherwise this function will exit. Use {@link lookup_pids/1} in these
  939. %% cases.
  940. %% @end
  941. %%
  942. where({T,_,_}=Key) ->
  943. if T==n orelse T==a ->
  944. case ets:lookup(?TAB, {Key,T}) of
  945. [{_, P, _Value}] ->
  946. case my_is_process_alive(P) of
  947. true -> P;
  948. false ->
  949. undefined
  950. end;
  951. _ -> % may be [] or [{Key,Waiters}]
  952. undefined
  953. end;
  954. true ->
  955. erlang:error(badarg)
  956. end.
  957. %% @equiv where/1
  958. whereis_name(Key) ->
  959. where(Key).
  960. %% @spec (Key::key()) -> [pid()]
  961. %%
  962. %% @doc Returns a list of pids with the published key Key
  963. %%
  964. %% If the type of registration entry is either name or aggregated counter,
  965. %% this function will return either an empty list, or a list of one pid.
  966. %% For non-unique types, the return value can be a list of any length.
  967. %% @end
  968. %%
  969. lookup_pids({T,_,_} = Key) ->
  970. L = if T==n orelse T==a ->
  971. ets:select(?TAB, [{{{Key,T}, '$1', '_'},[],['$1']}]);
  972. true ->
  973. ets:select(?TAB, [{{{Key,'_'}, '$1', '_'},[],['$1']}])
  974. end,
  975. [P || P <- L, my_is_process_alive(P)].
  976. %% @spec (pid()) -> boolean()
  977. %%
  978. my_is_process_alive(P) when node(P) =:= node() ->
  979. is_process_alive(P);
  980. my_is_process_alive(_) ->
  981. %% remote pid - assume true (too costly to find out)
  982. true.
  983. %% @spec (Key::key()) -> [{pid(), Value}]
  984. %%
  985. %% @doc Retrieve the `{Pid,Value}' pairs corresponding to Key.
  986. %%
  987. %% Key refer to any type of registry object. If it refers to a unique
  988. %% object, the list will be of length 0 or 1. If it refers to a non-unique
  989. %% object, the return value can be a list of any length.
  990. %% @end
  991. %%
  992. lookup_values({T,_,_} = Key) ->
  993. L = if T==n orelse T==a ->
  994. ets:select(?TAB, [{{{Key,T}, '$1', '$2'},[],[{{'$1','$2'}}]}]);
  995. true ->
  996. ets:select(?TAB, [{{{Key,'_'}, '$1', '$2'},[],[{{'$1','$2'}}]}])
  997. end,
  998. [Pair || {P,_} = Pair <- L, my_is_process_alive(P)].
  999. %% @spec (Key::key(), Incr::integer()) -> integer()
  1000. %%
  1001. %% @doc Updates the counter registered as Key for the current process.
  1002. %%
  1003. %% This function works like ets:update_counter/3
  1004. %% (see [http://www.erlang.org/doc/man/ets.html#update_counter-3]), but
  1005. %% will fail if the type of object referred to by Key is not a counter.
  1006. %% @end
  1007. %%
  1008. update_counter({c,l,_} = Key, Incr) when is_integer(Incr) ->
  1009. gproc_lib:update_counter(Key, Incr, self());
  1010. update_counter({c,g,_} = Key, Incr) when is_integer(Incr) ->
  1011. ?CHK_DIST,
  1012. gproc_dist:update_counter(Key, Incr);
  1013. update_counter(_, _) ->
  1014. erlang:error(badarg).
  1015. %% @spec (Key) -> {ValueBefore, ValueAfter}
  1016. %% Key = {c, Scope, Name}
  1017. %% Scope = l | g
  1018. %% ValueBefore = integer()
  1019. %% ValueAfter = integer()
  1020. %%
  1021. %% @doc Reads and resets a counter in a "thread-safe" way
  1022. %%
  1023. %% This function reads the current value of a counter and then resets it to its
  1024. %% initial value. The reset operation is done using {@link update_counter/2},
  1025. %% which allows for concurrent calls to {@link update_counter/2} without losing
  1026. %% updates. Aggregated counters are updated accordingly.
  1027. %% @end
  1028. %%
  1029. reset_counter({c,g,_} = Key) ->
  1030. ?CHK_DIST,
  1031. gproc_dist:reset_counter(Key);
  1032. reset_counter({c,l,_} = Key) ->
  1033. Current = ets:lookup_element(?TAB, {Key, self()}, 3),
  1034. Initial = case ets:lookup(?TAB, {self(), Key}) of
  1035. [{_, r}] -> 0;
  1036. [{_, Opts}] ->
  1037. proplists:get_value(initial, Opts, 0)
  1038. end,
  1039. {Current, update_counter(Key, Initial - Current)}.
  1040. update_shared_counter({c,g,_} = Key, Incr) ->
  1041. ?CHK_DIST,
  1042. gproc_dist:update_shared_counter(Key, Incr);
  1043. update_shared_counter({c,l,_} = Key, Incr) ->
  1044. gproc_lib:update_counter(Key, Incr, shared).
  1045. %% @spec (From::key(), To::pid() | key()) -> undefined | pid()
  1046. %%
  1047. %% @doc Atomically transfers the key `From' to the process identified by `To'.
  1048. %%
  1049. %% This function transfers any gproc key (name, property, counter, aggr counter)
  1050. %% from one process to another, and returns the pid of the new owner.
  1051. %%
  1052. %% `To' must be either a pid or a unique name (name or aggregated counter), but
  1053. %% does not necessarily have to resolve to an existing process. If there is
  1054. %% no process registered with the `To' key, `give_away/2' returns `undefined',
  1055. %% and the `From' key is effectively unregistered.
  1056. %%
  1057. %% It is allowed to give away a key to oneself, but of course, this operation
  1058. %% will have no effect.
  1059. %%
  1060. %% Fails with `badarg' if the calling process does not have a `From' key
  1061. %% registered.
  1062. %% @end
  1063. give_away({_,l,_} = Key, ToPid) when is_pid(ToPid), node(ToPid) == node() ->
  1064. call({give_away, Key, ToPid});
  1065. give_away({_,l,_} = Key, {n,l,_} = ToKey) ->
  1066. call({give_away, Key, ToKey});
  1067. give_away({_,g,_} = Key, To) ->
  1068. ?CHK_DIST,
  1069. gproc_dist:give_away(Key, To).
  1070. %% @spec () -> ok
  1071. %%
  1072. %% @doc Unregister all items of the calling process and inform gproc
  1073. %% to forget about the calling process.
  1074. %%
  1075. %% This function is more efficient than letting gproc perform these
  1076. %% cleanup operations.
  1077. %% @end
  1078. goodbye() ->
  1079. process_is_down(self()).
  1080. %% @spec (Key::key(), Msg::any()) -> Msg
  1081. %%
  1082. %% @doc Sends a message to the process, or processes, corresponding to Key.
  1083. %%
  1084. %% If Key belongs to a unique object (name or aggregated counter), this
  1085. %% function will send a message to the corresponding process, or fail if there
  1086. %% is no such process. If Key is for a non-unique object type (counter or
  1087. %% property), Msg will be send to all processes that have such an object.
  1088. %% @end
  1089. %%
  1090. send({T,C,_} = Key, Msg) when C==l; C==g ->
  1091. if T == n orelse T == a ->
  1092. case ets:lookup(?TAB, {Key, T}) of
  1093. [{_, Pid, _}] ->
  1094. Pid ! Msg;
  1095. _ ->
  1096. erlang:error(badarg)
  1097. end;
  1098. T==p orelse T==c ->
  1099. %% BUG - if the key part contains select wildcards, we may end up
  1100. %% sending multiple messages to the same pid
  1101. lists:foreach(fun(Pid) ->
  1102. Pid ! Msg
  1103. end, lookup_pids(Key)),
  1104. Msg;
  1105. true ->
  1106. erlang:error(badarg)
  1107. end;
  1108. send(_, _) ->
  1109. erlang:error(badarg).
  1110. %% @spec (Context :: context()) -> key() | '$end_of_table'
  1111. %%
  1112. %% @doc Behaves as ets:first(Tab) for a given type of registration object.
  1113. %%
  1114. %% See [http://www.erlang.org/doc/man/ets.html#first-1].
  1115. %% The registry behaves as an ordered_set table.
  1116. %% @end
  1117. %%
  1118. first(Context) ->
  1119. {S, T} = get_s_t(Context),
  1120. {HeadPat,_} = headpat({S, T}, '_', '_', '_'),
  1121. case ets:select(?TAB, [{HeadPat,[],[{element,1,'$_'}]}], 1) of
  1122. {[First], _} ->
  1123. First;
  1124. _ ->
  1125. '$end_of_table'
  1126. end.
  1127. %% @spec (Context :: context()) -> key() | '$end_of_table'
  1128. %%
  1129. %% @doc Behaves as ets:last(Tab) for a given type of registration object.
  1130. %%
  1131. %% See [http://www.erlang.org/doc/man/ets.html#last-1].
  1132. %% The registry behaves as an ordered_set table.
  1133. %% @end
  1134. %%
  1135. last(Context) ->
  1136. {S, T} = get_s_t(Context),
  1137. S1 = if S == '_'; S == l -> m; % 'm' comes after 'l'
  1138. S == g -> h % 'h' comes between 'g' & 'l'
  1139. end,
  1140. Beyond = {{T,S1,[]},[]},
  1141. step(ets:prev(?TAB, Beyond), S, T).
  1142. %% @spec (Context::context(), Key::key()) -> key() | '$end_of_table'
  1143. %%
  1144. %% @doc Behaves as ets:next(Tab,Key) for a given type of registration object.
  1145. %%
  1146. %% See [http://www.erlang.org/doc/man/ets.html#next-2].
  1147. %% The registry behaves as an ordered_set table.
  1148. %% @end
  1149. %%
  1150. next(Context, K) ->
  1151. {S,T} = get_s_t(Context),
  1152. step(ets:next(?TAB,K), S, T).
  1153. %% @spec (Context::context(), Key::key()) -> key() | '$end_of_table'
  1154. %%
  1155. %% @doc Behaves as ets:prev(Tab,Key) for a given type of registration object.
  1156. %%
  1157. %% See [http://www.erlang.org/doc/man/ets.html#prev-2].
  1158. %% The registry behaves as an ordered_set table.
  1159. %% @end
  1160. %%
  1161. prev(Context, K) ->
  1162. {S, T} = get_s_t(Context),
  1163. step(ets:prev(?TAB, K), S, T).
  1164. step(Key, '_', '_') ->
  1165. case Key of
  1166. {{_,_,_},_} -> Key;
  1167. _ -> '$end_of_table'
  1168. end;
  1169. step(Key, '_', T) ->
  1170. case Key of
  1171. {{T,_,_},_} -> Key;
  1172. _ -> '$end_of_table'
  1173. end;
  1174. step(Key, S, '_') ->
  1175. case Key of
  1176. {{_, S, _}, _} -> Key;
  1177. _ -> '$end_of_table'
  1178. end;
  1179. step(Key, S, T) ->
  1180. case Key of
  1181. {{T, S, _}, _} -> Key;
  1182. _ -> '$end_of_table'
  1183. end.
  1184. %% @spec (Pid::pid()) -> ProcessInfo
  1185. %% ProcessInfo = [{gproc, [{Key,Value}]} | ProcessInfo]
  1186. %%
  1187. %% @doc Similar to `process_info(Pid)' but with additional gproc info.
  1188. %%
  1189. %% Returns the same information as process_info(Pid), but with the
  1190. %% addition of a `gproc' information item, containing the `{Key,Value}'
  1191. %% pairs registered to the process.
  1192. %% @end
  1193. info(Pid) when is_pid(Pid) ->
  1194. Items = [?MODULE | [ I || {I,_} <- process_info(self())]],
  1195. [info(Pid,I) || I <- Items].
  1196. %% @spec (Pid::pid(), Item::atom()) -> {Item, Info}
  1197. %%
  1198. %% @doc Similar to process_info(Pid, Item), but with additional gproc info.
  1199. %%
  1200. %% For `Item = gproc', this function returns a list of `{Key, Value}' pairs
  1201. %% registered to the process Pid. For other values of Item, it returns the
  1202. %% same as [http://www.erlang.org/doc/man/erlang.html#process_info-2].
  1203. %% @end
  1204. info(Pid, ?MODULE) ->
  1205. Keys = ets:select(?TAB, [{ {{Pid,'$1'}, '_'}, [], ['$1'] }]),
  1206. {?MODULE, lists:zf(
  1207. fun(K) ->
  1208. try V = get_value(K, Pid),
  1209. {true, {K,V}}
  1210. catch
  1211. error:_ ->
  1212. false
  1213. end
  1214. end, Keys)};
  1215. info(Pid, I) ->
  1216. process_info(Pid, I).
  1217. %% @spec () -> ok
  1218. %%
  1219. %% @doc Similar to the built-in shell command `i()' but inserts information
  1220. %% about names and properties registered in Gproc, where applicable.
  1221. %% @end
  1222. i() ->
  1223. gproc_info:i().
  1224. %%% ==========================================================
  1225. %% @hidden
  1226. handle_cast({monitor_me, Pid}, S) ->
  1227. erlang:monitor(process, Pid),
  1228. {noreply, S};
  1229. handle_cast({cancel_wait, Pid, {T,_,_} = Key, Ref}, S) ->
  1230. Rev = {Pid,Key},
  1231. case ets:lookup(?TAB, {Key,T}) of
  1232. [{K, Waiters}] ->
  1233. case Waiters -- [{Pid,Ref}] of
  1234. [] ->
  1235. ets:delete(?TAB, K),
  1236. ets:delete(?TAB, Rev);
  1237. NewWaiters ->
  1238. ets:insert(?TAB, {K, NewWaiters}),
  1239. case lists:keymember(Pid, 1, NewWaiters) of
  1240. true ->
  1241. %% should be extremely unlikely
  1242. ok;
  1243. false ->
  1244. %% delete the reverse entry
  1245. ets:delete(?TAB, Rev)
  1246. end
  1247. end;
  1248. _ ->
  1249. ignore
  1250. end,
  1251. {noreply, S}.
  1252. %% @hidden
  1253. handle_call({reg, {_T,l,_} = Key, Val}, {Pid,_}, S) ->
  1254. case try_insert_reg(Key, Val, Pid) of
  1255. true ->
  1256. _ = gproc_lib:ensure_monitor(Pid,l),
  1257. {reply, true, S};
  1258. false ->
  1259. {reply, badarg, S}
  1260. end;
  1261. handle_call({monitor, {T,_,_} = Key}, {Pid, _}, S)
  1262. when T==n; T==a ->
  1263. Ref = make_ref(),
  1264. case where(Key) of
  1265. undefined ->
  1266. Pid ! {gproc, unreg, Ref, Key};
  1267. RegPid ->
  1268. case ets:lookup(?TAB, {RegPid, Key}) of
  1269. [{K,r}] ->
  1270. ets:insert(?TAB, {K, [{monitor, [Pid]}]});
  1271. [{K, Opts}] ->
  1272. ets:insert(?TAB, {K, add_monitor(Opts, Pid, Ref)})
  1273. end
  1274. end,
  1275. {reply, Ref, S};
  1276. handle_call({demonitor, {T,_,_} = Key, Ref}, {Pid,_}, S)
  1277. when T==n; T==a ->
  1278. case where(Key) of
  1279. undefined ->
  1280. ok; % be nice
  1281. RegPid ->
  1282. case ets:lookup(?TAB, {RegPid, Key}) of
  1283. [{_K,r}] ->
  1284. ok; % be nice
  1285. [{K, Opts}] ->
  1286. ets:insert(?TAB, {K, remove_monitor(Opts, Pid, Ref)})
  1287. end
  1288. end,
  1289. {reply, ok, S};
  1290. handle_call({reg_shared, {_T,l,_} = Key, Val}, _From, S) ->
  1291. case try_insert_reg(Key, Val, shared) of
  1292. %% case try_insert_shared(Key, Val) of
  1293. true ->
  1294. {reply, true, S};
  1295. false ->
  1296. {reply, badarg, S}
  1297. end;
  1298. handle_call({unreg, {_,l,_} = Key}, {Pid,_}, S) ->
  1299. case ets:lookup(?TAB, {Pid,Key}) of
  1300. [{_, r}] ->
  1301. _ = gproc_lib:remove_reg(Key, Pid),
  1302. {reply, true, S};
  1303. [{_, Opts}] when is_list(Opts) ->
  1304. _ = gproc_lib:remove_reg(Key, Pid, Opts),
  1305. {reply, true, S};
  1306. [] ->
  1307. {reply, badarg, S}
  1308. end;
  1309. handle_call({unreg_shared, {_,l,_} = Key}, _, S) ->
  1310. case ets:lookup(?TAB, {shared, Key}) of
  1311. [{_, r}] ->
  1312. _ = gproc_lib:remove_reg(Key, shared);
  1313. [{_, Opts}] ->
  1314. _ = gproc_lib:remove_reg(Key, shared, Opts);
  1315. [] ->
  1316. %% don't crash if shared key already unregged.
  1317. ok
  1318. end,
  1319. {reply, true, S};
  1320. handle_call({await, {_,l,_} = Key, Pid}, From, S) ->
  1321. %% Passing the pid explicitly is needed when leader_call is used,
  1322. %% since the Pid given as From in the leader is the local gen_leader
  1323. %% instance on the calling node.
  1324. case gproc_lib:await(Key, Pid, From) of
  1325. noreply ->
  1326. {noreply, S};
  1327. {reply, Reply, _} ->
  1328. {reply, Reply, S}
  1329. end;
  1330. handle_call({mreg, T, l, L}, {Pid,_}, S) ->
  1331. try gproc_lib:insert_many(T, l, L, Pid) of
  1332. {true,_} -> {reply, true, S};
  1333. false -> {reply, badarg, S}
  1334. catch
  1335. error:_ -> {reply, badarg, S}
  1336. end;
  1337. handle_call({munreg, T, l, L}, {Pid,_}, S) ->
  1338. _ = gproc_lib:remove_many(T, l, L, Pid),
  1339. {reply, true, S};
  1340. handle_call({set, {_,l,_} = Key, Value}, {Pid,_}, S) ->
  1341. case gproc_lib:do_set_value(Key, Value, Pid) of
  1342. true ->
  1343. {reply, true, S};
  1344. false ->
  1345. {reply, badarg, S}
  1346. end;
  1347. handle_call({audit_process, Pid}, _, S) ->
  1348. case is_process_alive(Pid) of
  1349. false ->
  1350. process_is_down(Pid);
  1351. true ->
  1352. ignore
  1353. end,
  1354. {reply, ok, S};
  1355. handle_call({give_away, Key, To}, {Pid,_}, S) ->
  1356. Reply = do_give_away(Key, To, Pid),
  1357. {reply, Reply, S};
  1358. handle_call(_, _, S) ->
  1359. {reply, badarg, S}.
  1360. %% @hidden
  1361. handle_info({'DOWN', _MRef, process, Pid, _}, S) ->
  1362. process_is_down(Pid),
  1363. {noreply, S};
  1364. handle_info(_, S) ->
  1365. {noreply, S}.
  1366. %% @hidden
  1367. code_change(_FromVsn, S, _Extra) ->
  1368. %% We have changed local monitor markers from {Pid} to {Pid,l}.
  1369. _ = case ets:select(?TAB, [{{'$1'},[],['$1']}]) of
  1370. [] ->
  1371. ok;
  1372. Pids ->
  1373. ets:insert(?TAB, [{P,l} || P <- Pids]),
  1374. ets:select_delete(?TAB, [{{'_'},[],[true]}])
  1375. end,
  1376. {ok, S}.
  1377. %% @hidden
  1378. terminate(_Reason, _S) ->
  1379. ok.
  1380. call(Req) ->
  1381. call(Req, l).
  1382. call(Req, l) ->
  1383. chk_reply(gen_server:call(?MODULE, Req), Req);
  1384. call(Req, g) ->
  1385. chk_reply(gproc_dist:leader_call(Req), Req).
  1386. chk_reply(Reply, Req) ->
  1387. case Reply of
  1388. badarg -> erlang:error(badarg, Req);
  1389. _ -> Reply
  1390. end.
  1391. cast(Msg) ->
  1392. cast(Msg, l).
  1393. cast(Msg, l) ->
  1394. gen_server:cast(?MODULE, Msg);
  1395. cast(Msg, g) ->
  1396. gproc_dist:leader_cast(Msg).
  1397. try_insert_reg({T,l,_} = Key, Val, Pid) ->
  1398. case gproc_lib:insert_reg(Key, Val, Pid, l) of
  1399. false ->
  1400. case ets:lookup(?TAB, {Key,T}) of
  1401. %% In this particular case, the lookup cannot result in
  1402. %% [{_, Waiters}], since the insert_reg/4 function would
  1403. %% have succeeded then.
  1404. [{_, OtherPid, _}] ->
  1405. case is_process_alive(OtherPid) of
  1406. true ->
  1407. false;
  1408. false ->
  1409. process_is_down(OtherPid),
  1410. true = gproc_lib:insert_reg(Key, Val, Pid, l)
  1411. end;
  1412. [] ->
  1413. false
  1414. end;
  1415. true ->
  1416. true
  1417. end.
  1418. %% try_insert_shared({c,l,_} = Key, Val) ->
  1419. %% ets:insert_new(?TAB, [{{Key,shared}, shared, Val}, {{shared, Key}, []}]);
  1420. %% try_insert_shared({a,l,_} = Key, Val) ->
  1421. %% ets:insert_new(?TAB, [{{Key, a}, shared, Val}, {{shared, Key}, []}]).
  1422. -spec audit_process(pid()) -> ok.
  1423. audit_process(Pid) when is_pid(Pid) ->
  1424. ok = gen_server:call(gproc, {audit_process, Pid}, infinity).
  1425. -spec process_is_down(pid()) -> ok.
  1426. process_is_down(Pid) when is_pid(Pid) ->
  1427. %% delete the monitor marker
  1428. %% io:fwrite(user, "process_is_down(~p) - ~p~n", [Pid,ets:tab2list(?TAB)]),
  1429. Marker = {Pid,l},
  1430. case ets:member(?TAB, Marker) of
  1431. false ->
  1432. ok;
  1433. true ->
  1434. Revs = ets:select(?TAB, [{{{Pid,'$1'}, '$2'},
  1435. [{'==',{element,2,'$1'},l}],
  1436. [{{'$1','$2'}}]}]),
  1437. lists:foreach(
  1438. fun({{n,l,_}=K, R}) ->
  1439. Key = {K,n},
  1440. case ets:lookup(?TAB, Key) of
  1441. [{_, Pid, _}] ->
  1442. ets:delete(?TAB, Key),
  1443. opt_notify(R, K);
  1444. [{_, Waiters}] ->
  1445. case [W || {P,_} = W <- Waiters,
  1446. P =/= Pid] of
  1447. [] ->
  1448. ets:delete(?TAB, Key);
  1449. Waiters1 ->
  1450. ets:insert(?TAB, {Key, Waiters1})
  1451. end;
  1452. [] ->
  1453. true
  1454. end;
  1455. ({{c,l,C} = K, _}) ->
  1456. Key = {K, Pid},
  1457. [{_, _, Value}] = ets:lookup(?TAB, Key),
  1458. ets:delete(?TAB, Key),
  1459. gproc_lib:update_aggr_counter(l, C, -Value);
  1460. ({{a,l,_} = K, R}) ->
  1461. ets:delete(?TAB, {K,a}),
  1462. opt_notify(R, K);
  1463. ({{p,_,_} = K, _}) ->
  1464. ets:delete(?TAB, {K, Pid})
  1465. end, Revs),
  1466. ets:select_delete(?TAB, [{{{Pid,{'_',l,'_'}},'_'}, [], [true]}]),
  1467. ets:delete(?TAB, Marker),
  1468. ok
  1469. end.
  1470. opt_notify(r, _) ->
  1471. ok;
  1472. opt_notify(Opts, Key) ->
  1473. gproc_lib:notify(Key, Opts).
  1474. do_give_away({T,l,_} = K, To, Pid) when T==n; T==a ->
  1475. Key = {K, T},
  1476. case ets:lookup(?TAB, Key) of
  1477. [{_, Pid, Value}] ->
  1478. %% Pid owns the reg; allowed to give_away
  1479. case pid_to_give_away_to(To) of
  1480. Pid ->
  1481. %% Give away to ourselves? Why not? We'll allow it,
  1482. %% but nothing needs to be done.
  1483. Pid;
  1484. ToPid when is_pid(ToPid) ->
  1485. ets:insert(?TAB, [{Key, ToPid, Value},
  1486. {{ToPid, K}, []}]),
  1487. ets:delete(?TAB, {Pid, K}),
  1488. _ = gproc_lib:ensure_monitor(ToPid, l),
  1489. ToPid;
  1490. undefined ->
  1491. _ = gproc_lib:remove_reg(K, Pid),
  1492. undefined
  1493. end;
  1494. _ ->
  1495. badarg
  1496. end;
  1497. do_give_away({T,l,_} = K, To, Pid) when T==c; T==p ->
  1498. Key = {K, Pid},
  1499. case ets:lookup(?TAB, Key) of
  1500. [{_, Pid, Value}] ->
  1501. case pid_to_give_away_to(To) of
  1502. ToPid when is_pid(ToPid) ->
  1503. ToKey = {K, ToPid},
  1504. case ets:member(?TAB, ToKey) of
  1505. true ->
  1506. badarg;
  1507. false ->
  1508. ets:insert(?TAB, [{ToKey, ToPid, Value},
  1509. {{ToPid, K}, []}]),
  1510. ets:delete(?TAB, {Pid, K}),
  1511. ets:delete(?TAB, Key),
  1512. _ = gproc_lib:ensure_monitor(ToPid, l),
  1513. ToPid
  1514. end;
  1515. undefined ->
  1516. _ = gproc_lib:remove_reg(K, Pid),
  1517. undefined
  1518. end;
  1519. _ ->
  1520. badarg
  1521. end.
  1522. pid_to_give_away_to(P) when is_pid(P), node(P) == node() ->
  1523. P;
  1524. pid_to_give_away_to({T,l,_} = Key) when T==n; T==a ->
  1525. case ets:lookup(?TAB, {Key, T}) of
  1526. [{_, Pid, _}] ->
  1527. Pid;
  1528. _ ->
  1529. undefined
  1530. end.
  1531. create_tabs() ->
  1532. Opts = gproc_lib:valid_opts(ets_options, [{write_concurrency,true},
  1533. {read_concurrency, true}]),
  1534. case ets:info(?TAB, name) of
  1535. undefined ->
  1536. ets:new(?TAB, [ordered_set, public, named_table | Opts]);
  1537. _ ->
  1538. ok
  1539. end.
  1540. %% @hidden
  1541. init([]) ->
  1542. set_monitors(),
  1543. {ok, #state{}}.
  1544. set_monitors() ->
  1545. set_monitors(ets:select(?TAB, [{{{'$1',l}},[],['$1']}], 100)).
  1546. set_monitors('$end_of_table') ->
  1547. ok;
  1548. set_monitors({Pids, Cont}) ->
  1549. _ = [erlang:monitor(process,Pid) || Pid <- Pids],
  1550. set_monitors(ets:select(Cont)).
  1551. add_monitor([{monitor, Mons}|T], Pid, Ref) ->
  1552. [{monitor, [{Pid,Ref}|Mons]}|T];
  1553. add_monitor([H|T], Pid, Ref) ->
  1554. [H|add_monitor(T, Pid, Ref)];
  1555. add_monitor([], Pid, Ref) ->
  1556. [{monitor, [{Pid, Ref}]}].
  1557. remove_monitor([{monitor, Mons}|T], Pid, Ref) ->
  1558. [{monitor, Mons -- [{Pid, Ref}]}|T];
  1559. remove_monitor([H|T], Pid, Ref) ->
  1560. [H|remove_monitor(T, Pid, Ref)];
  1561. remove_monitor([], _Pid, _Ref) ->
  1562. [].
  1563. monitor_me() ->
  1564. case ets:insert_new(?TAB, {{self(),l}}) of
  1565. false -> true;
  1566. true ->
  1567. cast({monitor_me,self()}),
  1568. true
  1569. end.
  1570. pattern([{'_', Gs, As}], T) ->
  1571. ?l,
  1572. {HeadPat, Vs} = headpat(T, '$1', '$2', '$3'),
  1573. [{HeadPat, rewrite(Gs,Vs), rewrite(As,Vs)}];
  1574. pattern([{{A,B,C},Gs,As}], Scope) ->
  1575. ?l,
  1576. {HeadPat, Vars} = headpat(Scope, A,B,C),
  1577. [{HeadPat, rewrite(Gs,Vars), rewrite(As,Vars)}];
  1578. pattern([{Head, Gs, As}], Scope) ->
  1579. ?l,
  1580. {S, T} = get_s_t(Scope),
  1581. case is_var(Head) of
  1582. {true,_N} ->
  1583. HeadPat = {{{T,S,'_'},'_'},'_','_'},
  1584. Vs = [{Head, obj_prod()}],
  1585. %% the headpat function should somehow verify that Head is
  1586. %% consistent with Scope (or should we add a guard?)
  1587. [{HeadPat, rewrite(Gs, Vs), rewrite(As, Vs)}];
  1588. false ->
  1589. erlang:error(badarg)
  1590. end.
  1591. %% This is the expression to use in guards and the RHS to address the whole
  1592. %% object, in its logical representation.
  1593. obj_prod() ->
  1594. {{ {element,1,{element,1,'$_'}},
  1595. {element,2,'$_'},
  1596. {element,3,'$_'} }}.
  1597. obj_prod_l() ->
  1598. [ {element,1,{element,1,'$_'}},
  1599. {element,2,'$_'},
  1600. {element,3,'$_'} ].
  1601. headpat({S, T}, V1,V2,V3) ->
  1602. headpat(type(T), scope(S), V1,V2,V3);
  1603. headpat(T, V1, V2, V3) when is_atom(T) ->
  1604. headpat(type(T), l, V1, V2, V3);
  1605. headpat(_, _, _, _) -> erlang:error(badarg).
  1606. headpat(T, C, V1,V2,V3) ->
  1607. Rf = fun(Pos) ->
  1608. {element,Pos,{element,1,{element,1,'$_'}}}
  1609. end,
  1610. K2 = if T==n orelse T==a -> T;
  1611. true -> '_'
  1612. end,
  1613. {Kp,Vars} = case V1 of
  1614. {Vt,Vc,Vn} ->
  1615. ?l,
  1616. {T1,Vs1} = subst(T,Vt,fun() -> Rf(1) end,[]),
  1617. {C1,Vs2} = subst(C,Vc,fun() -> Rf(2) end,Vs1),
  1618. {{T1,C1,Vn}, Vs2};
  1619. '_' ->
  1620. ?l,
  1621. {{T,C,'_'}, []};
  1622. _ ->
  1623. ?l,
  1624. case is_var(V1) of
  1625. {true,_} ->
  1626. {{T,C,V1}, [{V1, {element,1,
  1627. {element,1,'$_'}}}]};
  1628. false ->
  1629. erlang:error(badarg)
  1630. end
  1631. end,
  1632. {{{Kp,K2},V2,V3}, Vars}.
  1633. %% l(L) -> L.
  1634. subst(X, '_', _F, Vs) ->
  1635. {X, Vs};
  1636. subst(X, V, F, Vs) ->
  1637. case is_var(V) of
  1638. {true,_} ->
  1639. {X, [{V,F()}|Vs]};
  1640. false ->
  1641. {V, Vs}
  1642. end.
  1643. scope('_') -> '_';
  1644. scope(all) -> '_';
  1645. scope(global) -> g;
  1646. scope(local) -> l;
  1647. scope(S) when S==l; S==g -> S.
  1648. type('_') -> '_';
  1649. type(all) -> '_';
  1650. type(T) when T==n; T==p; T==c; T==a -> T;
  1651. type(names) -> n;
  1652. type(props) -> p;
  1653. type(counters) -> c;
  1654. type(aggr_counters) -> a.
  1655. rev_keypat(Context) ->
  1656. {S,T} = get_s_t(Context),
  1657. {T,S,'_'}.
  1658. get_s_t({S,T}) -> {scope(S), type(T)};
  1659. get_s_t(T) when is_atom(T) ->
  1660. {scope(all), type(T)}.
  1661. is_var('$1') -> {true,1};
  1662. is_var('$2') -> {true,2};
  1663. is_var('$3') -> {true,3};
  1664. is_var('$4') -> {true,4};
  1665. is_var('$5') -> {true,5};
  1666. is_var('$6') -> {true,6};
  1667. is_var('$7') -> {true,7};
  1668. is_var('$8') -> {true,8};
  1669. is_var('$9') -> {true,9};
  1670. is_var(X) when is_atom(X) ->
  1671. case atom_to_list(X) of
  1672. "\$" ++ Tl ->
  1673. try N = list_to_integer(Tl),
  1674. {true,N}
  1675. catch
  1676. error:_ ->
  1677. false
  1678. end;
  1679. _ ->
  1680. false
  1681. end;
  1682. is_var(_) -> false.
  1683. rewrite(Gs, R) ->
  1684. [rewrite1(G, R) || G <- Gs].
  1685. rewrite1('$_', _) ->
  1686. obj_prod();
  1687. rewrite1('$$', _) ->
  1688. obj_prod_l();
  1689. rewrite1(Guard, R) when is_tuple(Guard) ->
  1690. list_to_tuple([rewrite1(G, R) || G <- tuple_to_list(Guard)]);
  1691. rewrite1(Exprs, R) when is_list(Exprs) ->
  1692. [rewrite1(E, R) || E <- Exprs];
  1693. rewrite1(V, R) when is_atom(V) ->
  1694. case is_var(V) of
  1695. {true,_N} ->
  1696. case lists:keysearch(V, 1, R) of
  1697. {value, {_, V1}} ->
  1698. V1;
  1699. false ->
  1700. V
  1701. end;
  1702. false ->
  1703. V
  1704. end;
  1705. rewrite1(Expr, _) ->
  1706. Expr.
  1707. %% @spec () -> any()
  1708. %%
  1709. %% @doc
  1710. %% @equiv table({all, all})
  1711. %% @end
  1712. table() ->
  1713. table({all, all}).
  1714. %% @spec (Context::context()) -> any()
  1715. %%
  1716. %% @doc
  1717. %% @equiv table(Context, [])
  1718. %% @end
  1719. %%
  1720. table(Context) ->
  1721. table(Context, []).
  1722. %% @spec (Context::context(), Opts) -> any()
  1723. %%
  1724. %% @doc QLC table generator for the gproc registry.
  1725. %% Context specifies which subset of the registry should be queried.
  1726. %% See [http://www.erlang.org/doc/man/qlc.html].
  1727. %% @end
  1728. table(Context, Opts) ->
  1729. Ctxt = {_, Type} = get_s_t(Context),
  1730. [Traverse, NObjs] = [proplists:get_value(K,Opts,Def) ||
  1731. {K,Def} <- [{traverse,select}, {n_objects,100}]],
  1732. TF = case Traverse of
  1733. first_next ->
  1734. fun() -> qlc_next(Ctxt, first(Ctxt)) end;
  1735. last_prev -> fun() -> qlc_prev(Ctxt, last(Ctxt)) end;
  1736. select ->
  1737. fun(MS) -> qlc_select(select(Ctxt, MS, NObjs)) end;
  1738. {select,MS} ->
  1739. fun() -> qlc_select(select(Ctxt, MS, NObjs)) end;
  1740. _ ->
  1741. erlang:error(badarg, [Ctxt,Opts])
  1742. end,
  1743. InfoFun = fun(indices) -> [2];
  1744. (is_unique_objects) -> is_unique(Type);
  1745. (keypos) -> 1;
  1746. (is_sorted_key) -> true;
  1747. (num_of_objects) ->
  1748. %% this is just a guesstimate.
  1749. trunc(ets:info(?TAB,size) / 2.5)
  1750. end,
  1751. LookupFun =
  1752. case Traverse of
  1753. {select, _MS} -> undefined;
  1754. _ -> fun(Pos, Ks) -> qlc_lookup(Ctxt, Pos, Ks) end
  1755. end,
  1756. qlc:table(TF, [{info_fun, InfoFun},
  1757. {lookup_fun, LookupFun}] ++ [{K,V} || {K,V} <- Opts,
  1758. K =/= traverse,
  1759. K =/= n_objects]).
  1760. qlc_lookup(_Scope, 1, Keys) ->
  1761. lists:flatmap(
  1762. fun(Key) ->
  1763. ets:select(?TAB, [{ {{Key,'_'},'_','_'}, [],
  1764. [{{ {element,1,{element,1,'$_'}},
  1765. {element,2,'$_'},
  1766. {element,3,'$_'} }}] }])
  1767. end, Keys);
  1768. qlc_lookup(Scope, 2, Pids) ->
  1769. lists:flatmap(fun(Pid) ->
  1770. Found =
  1771. ets:select(?TAB, [{{{Pid, rev_keypat(Scope)}, '_'},
  1772. [], ['$_']}]),
  1773. lists:flatmap(
  1774. fun({{_,{T,_,_}=K}, _}) ->
  1775. K2 = if T==n orelse T==a -> T;
  1776. true -> Pid
  1777. end,
  1778. case ets:lookup(?TAB, {K,K2}) of
  1779. [{{Key,_},_,Value}] ->
  1780. [{Key, Pid, Value}];
  1781. [] ->
  1782. []
  1783. end
  1784. end, Found)
  1785. end, Pids).
  1786. qlc_next(_, '$end_of_table') -> [];
  1787. qlc_next(Scope, K) ->
  1788. case ets:lookup(?TAB, K) of
  1789. [{{Key,_}, Pid, V}] ->
  1790. [{Key,Pid,V}] ++ fun() -> qlc_next(Scope, next(Scope, K)) end;
  1791. [] ->
  1792. qlc_next(Scope, next(Scope, K))
  1793. end.
  1794. qlc_prev(_, '$end_of_table') -> [];
  1795. qlc_prev(Scope, K) ->
  1796. case ets:lookup(?TAB, K) of
  1797. [{{Key,_},Pid,V}] ->
  1798. [{Key,Pid,V}] ++ fun() -> qlc_prev(Scope, prev(Scope, K)) end;
  1799. [] ->
  1800. qlc_prev(Scope, prev(Scope, K))
  1801. end.
  1802. qlc_select('$end_of_table') ->
  1803. [];
  1804. qlc_select({Objects, Cont}) ->
  1805. Objects ++ fun() -> qlc_select(ets:select(Cont)) end.
  1806. is_unique(n) -> true;
  1807. is_unique(a) -> true;
  1808. is_unique(_) -> false.