emqx_shared_sub.erl 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved.
  3. %%
  4. %% Licensed under the Apache License, Version 2.0 (the "License");
  5. %% you may not use this file except in compliance with the License.
  6. %% You may obtain a copy of the License at
  7. %%
  8. %% http://www.apache.org/licenses/LICENSE-2.0
  9. %%
  10. %% Unless required by applicable law or agreed to in writing, software
  11. %% distributed under the License is distributed on an "AS IS" BASIS,
  12. %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. %% See the License for the specific language governing permissions and
  14. %% limitations under the License.
  15. %%--------------------------------------------------------------------
  16. -module(emqx_shared_sub).
  17. -behaviour(gen_server).
  18. -include("emqx.hrl").
  19. -include("emqx_mqtt.hrl").
  20. -include("logger.hrl").
  21. -include("types.hrl").
  22. -logger_header("[Shared Sub]").
  23. %% Mnesia bootstrap
  24. -export([mnesia/1]).
  25. -boot_mnesia({mnesia, [boot]}).
  26. -copy_mnesia({mnesia, [copy]}).
  27. %% APIs
  28. -export([start_link/0]).
  29. -export([ subscribe/3
  30. , unsubscribe/3
  31. ]).
  32. -export([dispatch/3]).
  33. -export([ maybe_ack/1
  34. , maybe_nack_dropped/1
  35. , nack_no_connection/1
  36. , is_ack_required/1
  37. ]).
  38. %% for testing
  39. -export([subscribers/2]).
  40. %% gen_server callbacks
  41. -export([ init/1
  42. , handle_call/3
  43. , handle_cast/2
  44. , handle_info/2
  45. , terminate/2
  46. , code_change/3
  47. ]).
  48. -export_type([strategy/0]).
  49. -type strategy() :: random
  50. | round_robin
  51. | sticky
  52. | hash %% same as hash_clientid, backward compatible
  53. | hash_clientid
  54. | hash_topic.
  55. -define(SERVER, ?MODULE).
  56. -define(TAB, emqx_shared_subscription).
  57. -define(SHARED_SUBS, emqx_shared_subscriber).
  58. -define(ALIVE_SUBS, emqx_alive_shared_subscribers).
  59. -define(SHARED_SUB_QOS1_DISPATCH_TIMEOUT_SECONDS, 5).
  60. -define(IS_LOCAL_PID(Pid), (is_pid(Pid) andalso node(Pid) =:= node())).
  61. -define(ACK, shared_sub_ack).
  62. -define(NACK(Reason), {shared_sub_nack, Reason}).
  63. -define(NO_ACK, no_ack).
  64. -record(state, {pmon}).
  65. -record(emqx_shared_subscription, {group, topic, subpid}).
  66. %%--------------------------------------------------------------------
  67. %% Mnesia bootstrap
  68. %%--------------------------------------------------------------------
  69. mnesia(boot) ->
  70. ok = ekka_mnesia:create_table(?TAB, [
  71. {type, bag},
  72. {ram_copies, [node()]},
  73. {record_name, emqx_shared_subscription},
  74. {attributes, record_info(fields, emqx_shared_subscription)}]);
  75. mnesia(copy) ->
  76. ok = ekka_mnesia:copy_table(?TAB, ram_copies).
  77. %%--------------------------------------------------------------------
  78. %% API
  79. %%--------------------------------------------------------------------
  80. -spec(start_link() -> startlink_ret()).
  81. start_link() ->
  82. gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
  83. -spec(subscribe(emqx_topic:group(), emqx_topic:topic(), pid()) -> ok).
  84. subscribe(Group, Topic, SubPid) when is_pid(SubPid) ->
  85. gen_server:call(?SERVER, {subscribe, Group, Topic, SubPid}).
  86. -spec(unsubscribe(emqx_topic:group(), emqx_topic:topic(), pid()) -> ok).
  87. unsubscribe(Group, Topic, SubPid) when is_pid(SubPid) ->
  88. gen_server:call(?SERVER, {unsubscribe, Group, Topic, SubPid}).
  89. record(Group, Topic, SubPid) ->
  90. #emqx_shared_subscription{group = Group, topic = Topic, subpid = SubPid}.
  91. -spec(dispatch(emqx_topic:group(), emqx_topic:topic(), emqx_types:delivery())
  92. -> emqx_types:deliver_result()).
  93. dispatch(Group, Topic, Delivery) ->
  94. dispatch(Group, Topic, Delivery, _FailedSubs = []).
  95. dispatch(Group, Topic, Delivery = #delivery{message = Msg}, FailedSubs) ->
  96. #message{from = ClientId, topic = SourceTopic} = Msg,
  97. case pick(strategy(), ClientId, SourceTopic, Group, Topic, FailedSubs) of
  98. false ->
  99. {error, no_subscribers};
  100. {Type, SubPid} ->
  101. case do_dispatch(SubPid, Topic, Msg, Type) of
  102. ok -> {ok, 1};
  103. {error, _Reason} ->
  104. %% Failed to dispatch to this sub, try next.
  105. dispatch(Group, Topic, Delivery, [SubPid | FailedSubs])
  106. end
  107. end.
  108. -spec(strategy() -> strategy()).
  109. strategy() ->
  110. emqx:get_env(shared_subscription_strategy, random).
  111. -spec(ack_enabled() -> boolean()).
  112. ack_enabled() ->
  113. emqx:get_env(shared_dispatch_ack_enabled, false).
  114. do_dispatch(SubPid, Topic, Msg, _Type) when SubPid =:= self() ->
  115. %% Deadlock otherwise
  116. _ = erlang:send(SubPid, {deliver, Topic, Msg}),
  117. ok;
  118. do_dispatch(SubPid, Topic, Msg, Type) ->
  119. dispatch_per_qos(SubPid, Topic, Msg, Type).
  120. %% return either 'ok' (when everything is fine) or 'error'
  121. dispatch_per_qos(SubPid, Topic, #message{qos = ?QOS_0} = Msg, _Type) ->
  122. %% For QoS 0 message, send it as regular dispatch
  123. _ = erlang:send(SubPid, {deliver, Topic, Msg}),
  124. ok;
  125. dispatch_per_qos(SubPid, Topic, Msg, retry) ->
  126. %% Retry implies all subscribers nack:ed, send again without ack
  127. _ = erlang:send(SubPid, {deliver, Topic, Msg}),
  128. ok;
  129. dispatch_per_qos(SubPid, Topic, Msg, fresh) ->
  130. case ack_enabled() of
  131. true ->
  132. dispatch_with_ack(SubPid, Topic, Msg);
  133. false ->
  134. _ = erlang:send(SubPid, {deliver, Topic, Msg}),
  135. ok
  136. end.
  137. dispatch_with_ack(SubPid, Topic, Msg) ->
  138. %% For QoS 1/2 message, expect an ack
  139. Ref = erlang:monitor(process, SubPid),
  140. Sender = self(),
  141. _ = erlang:send(SubPid, {deliver, Topic, with_ack_ref(Msg, {Sender, Ref})}),
  142. Timeout = case Msg#message.qos of
  143. ?QOS_1 -> timer:seconds(?SHARED_SUB_QOS1_DISPATCH_TIMEOUT_SECONDS);
  144. ?QOS_2 -> infinity
  145. end,
  146. try
  147. receive
  148. {Ref, ?ACK} ->
  149. ok;
  150. {Ref, ?NACK(Reason)} ->
  151. %% the receive session may nack this message when its queue is full
  152. {error, Reason};
  153. {'DOWN', Ref, process, SubPid, Reason} ->
  154. {error, Reason}
  155. after
  156. Timeout ->
  157. {error, timeout}
  158. end
  159. after
  160. _ = erlang:demonitor(Ref, [flush])
  161. end.
  162. with_ack_ref(Msg, SenderRef) ->
  163. emqx_message:set_headers(#{shared_dispatch_ack => SenderRef}, Msg).
  164. without_ack_ref(Msg) ->
  165. emqx_message:set_headers(#{shared_dispatch_ack => ?NO_ACK}, Msg).
  166. get_ack_ref(Msg) ->
  167. emqx_message:get_header(shared_dispatch_ack, Msg, ?NO_ACK).
  168. -spec(is_ack_required(emqx_types:message()) -> boolean()).
  169. is_ack_required(Msg) -> ?NO_ACK =/= get_ack_ref(Msg).
  170. %% @doc Negative ack dropped message due to inflight window or message queue being full.
  171. -spec(maybe_nack_dropped(emqx_types:message()) -> ok).
  172. maybe_nack_dropped(Msg) ->
  173. case get_ack_ref(Msg) of
  174. ?NO_ACK -> ok;
  175. {Sender, Ref} -> nack(Sender, Ref, dropped)
  176. end.
  177. %% @doc Negative ack message due to connection down.
  178. %% Assuming this function is always called when ack is required
  179. %% i.e is_ack_required returned true.
  180. -spec(nack_no_connection(emqx_types:message()) -> ok).
  181. nack_no_connection(Msg) ->
  182. {Sender, Ref} = get_ack_ref(Msg),
  183. nack(Sender, Ref, no_connection).
  184. -spec(nack(pid(), reference(), dropped | no_connection) -> ok).
  185. nack(Sender, Ref, Reason) ->
  186. erlang:send(Sender, {Ref, ?NACK(Reason)}),
  187. ok.
  188. -spec(maybe_ack(emqx_types:message()) -> emqx_types:message()).
  189. maybe_ack(Msg) ->
  190. case get_ack_ref(Msg) of
  191. ?NO_ACK ->
  192. Msg;
  193. {Sender, Ref} ->
  194. erlang:send(Sender, {Ref, ?ACK}),
  195. without_ack_ref(Msg)
  196. end.
  197. pick(sticky, ClientId, SourceTopic, Group, Topic, FailedSubs) ->
  198. Sub0 = erlang:get({shared_sub_sticky, Group, Topic}),
  199. case is_active_sub(Sub0, FailedSubs) of
  200. true ->
  201. %% the old subscriber is still alive
  202. %% keep using it for sticky strategy
  203. {fresh, Sub0};
  204. false ->
  205. %% randomly pick one for the first message
  206. {Type, Sub} = do_pick(random, ClientId, SourceTopic, Group, Topic, [Sub0 | FailedSubs]),
  207. %% stick to whatever pick result
  208. erlang:put({shared_sub_sticky, Group, Topic}, Sub),
  209. {Type, Sub}
  210. end;
  211. pick(Strategy, ClientId, SourceTopic, Group, Topic, FailedSubs) ->
  212. do_pick(Strategy, ClientId, SourceTopic, Group, Topic, FailedSubs).
  213. do_pick(Strategy, ClientId, SourceTopic, Group, Topic, FailedSubs) ->
  214. All = subscribers(Group, Topic),
  215. case All -- FailedSubs of
  216. [] when All =:= [] ->
  217. %% Genuinely no subscriber
  218. false;
  219. [] ->
  220. %% All offline? pick one anyway
  221. {retry, pick_subscriber(Group, Topic, Strategy, ClientId, SourceTopic, All)};
  222. Subs ->
  223. %% More than one available
  224. {fresh, pick_subscriber(Group, Topic, Strategy, ClientId, SourceTopic, Subs)}
  225. end.
  226. pick_subscriber(_Group, _Topic, _Strategy, _ClientId, _SourceTopic, [Sub]) -> Sub;
  227. pick_subscriber(Group, Topic, Strategy, ClientId, SourceTopic, Subs) ->
  228. Nth = do_pick_subscriber(Group, Topic, Strategy, ClientId, SourceTopic, length(Subs)),
  229. lists:nth(Nth, Subs).
  230. do_pick_subscriber(_Group, _Topic, random, _ClientId, _SourceTopic, Count) ->
  231. rand:uniform(Count);
  232. do_pick_subscriber(Group, Topic, hash, ClientId, SourceTopic, Count) ->
  233. %% backward compatible
  234. do_pick_subscriber(Group, Topic, hash_clientid, ClientId, SourceTopic, Count);
  235. do_pick_subscriber(_Group, _Topic, hash_clientid, ClientId, _SourceTopic, Count) ->
  236. 1 + erlang:phash2(ClientId) rem Count;
  237. do_pick_subscriber(_Group, _Topic, hash_topic, _ClientId, SourceTopic, Count) ->
  238. 1 + erlang:phash2(SourceTopic) rem Count;
  239. do_pick_subscriber(Group, Topic, round_robin, _ClientId, _SourceTopic, Count) ->
  240. Rem = case erlang:get({shared_sub_round_robin, Group, Topic}) of
  241. undefined -> rand:uniform(Count) - 1;
  242. N -> (N + 1) rem Count
  243. end,
  244. _ = erlang:put({shared_sub_round_robin, Group, Topic}, Rem),
  245. Rem + 1.
  246. subscribers(Group, Topic) ->
  247. ets:select(?TAB, [{{emqx_shared_subscription, Group, Topic, '$1'}, [], ['$1']}]).
  248. %%--------------------------------------------------------------------
  249. %% gen_server callbacks
  250. %%--------------------------------------------------------------------
  251. init([]) ->
  252. {ok, _} = mnesia:subscribe({table, ?TAB, simple}),
  253. {atomic, PMon} = mnesia:transaction(fun init_monitors/0),
  254. ok = emqx_tables:new(?SHARED_SUBS, [protected, bag]),
  255. ok = emqx_tables:new(?ALIVE_SUBS, [protected, set, {read_concurrency, true}]),
  256. {ok, update_stats(#state{pmon = PMon})}.
  257. init_monitors() ->
  258. mnesia:foldl(
  259. fun(#emqx_shared_subscription{subpid = SubPid}, Mon) ->
  260. emqx_pmon:monitor(SubPid, Mon)
  261. end, emqx_pmon:new(), ?TAB).
  262. handle_call({subscribe, Group, Topic, SubPid}, _From, State = #state{pmon = PMon}) ->
  263. mnesia:dirty_write(?TAB, record(Group, Topic, SubPid)),
  264. case ets:member(?SHARED_SUBS, {Group, Topic}) of
  265. true -> ok;
  266. false -> ok = emqx_router:do_add_route(Topic, {Group, node()})
  267. end,
  268. ok = maybe_insert_alive_tab(SubPid),
  269. true = ets:insert(?SHARED_SUBS, {{Group, Topic}, SubPid}),
  270. {reply, ok, update_stats(State#state{pmon = emqx_pmon:monitor(SubPid, PMon)})};
  271. handle_call({unsubscribe, Group, Topic, SubPid}, _From, State) ->
  272. mnesia:dirty_delete_object(?TAB, record(Group, Topic, SubPid)),
  273. true = ets:delete_object(?SHARED_SUBS, {{Group, Topic}, SubPid}),
  274. delete_route_if_needed({Group, Topic}),
  275. {reply, ok, State};
  276. handle_call(Req, _From, State) ->
  277. ?LOG(error, "Unexpected call: ~p", [Req]),
  278. {reply, ignored, State}.
  279. handle_cast(Msg, State) ->
  280. ?LOG(error, "Unexpected cast: ~p", [Msg]),
  281. {noreply, State}.
  282. handle_info({mnesia_table_event, {write, NewRecord, _}}, State = #state{pmon = PMon}) ->
  283. #emqx_shared_subscription{subpid = SubPid} = NewRecord,
  284. {noreply, update_stats(State#state{pmon = emqx_pmon:monitor(SubPid, PMon)})};
  285. handle_info({mnesia_table_event, {delete_object, OldRecord, _}}, State = #state{pmon = PMon}) ->
  286. #emqx_shared_subscription{subpid = SubPid} = OldRecord,
  287. {noreply, update_stats(State#state{pmon = emqx_pmon:demonitor(SubPid, PMon)})};
  288. handle_info({mnesia_table_event, _Event}, State) ->
  289. {noreply, State};
  290. handle_info({'DOWN', _MRef, process, SubPid, _Reason}, State = #state{pmon = PMon}) ->
  291. ?LOG(info, "Shared subscriber down: ~p", [SubPid]),
  292. cleanup_down(SubPid),
  293. {noreply, update_stats(State#state{pmon = emqx_pmon:erase(SubPid, PMon)})};
  294. handle_info(Info, State) ->
  295. ?LOG(error, "Unexpected info: ~p", [Info]),
  296. {noreply, State}.
  297. terminate(_Reason, _State) ->
  298. mnesia:unsubscribe({table, ?TAB, simple}).
  299. code_change(_OldVsn, State, _Extra) ->
  300. {ok, State}.
  301. %%--------------------------------------------------------------------
  302. %% Internal functions
  303. %%--------------------------------------------------------------------
  304. %% keep track of alive remote pids
  305. maybe_insert_alive_tab(Pid) when ?IS_LOCAL_PID(Pid) -> ok;
  306. maybe_insert_alive_tab(Pid) when is_pid(Pid) -> ets:insert(?ALIVE_SUBS, {Pid}), ok.
  307. cleanup_down(SubPid) ->
  308. ?IS_LOCAL_PID(SubPid) orelse ets:delete(?ALIVE_SUBS, SubPid),
  309. lists:foreach(
  310. fun(Record = #emqx_shared_subscription{topic = Topic, group = Group}) ->
  311. ok = mnesia:dirty_delete_object(?TAB, Record),
  312. true = ets:delete_object(?SHARED_SUBS, {{Group, Topic}, SubPid}),
  313. delete_route_if_needed({Group, Topic})
  314. end, mnesia:dirty_match_object(#emqx_shared_subscription{_ = '_', subpid = SubPid})).
  315. update_stats(State) ->
  316. emqx_stats:setstat('subscriptions.shared.count',
  317. 'subscriptions.shared.max',
  318. ets:info(?TAB, size)
  319. ),
  320. State.
  321. %% Return 'true' if the subscriber process is alive AND not in the failed list
  322. is_active_sub(Pid, FailedSubs) ->
  323. is_alive_sub(Pid) andalso not lists:member(Pid, FailedSubs).
  324. %% erlang:is_process_alive/1 does not work with remote pid.
  325. is_alive_sub(Pid) when ?IS_LOCAL_PID(Pid) ->
  326. erlang:is_process_alive(Pid);
  327. is_alive_sub(Pid) ->
  328. [] =/= ets:lookup(?ALIVE_SUBS, Pid).
  329. delete_route_if_needed({Group, Topic}) ->
  330. case ets:member(?SHARED_SUBS, {Group, Topic}) of
  331. true -> ok;
  332. false -> ok = emqx_router:do_delete_route(Topic, {Group, node()})
  333. end.