design.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. .. _design:
  2. ============
  3. Design Guide
  4. ============
  5. .. _design_architecture:
  6. ------------
  7. Architecture
  8. ------------
  9. The emqttd broker 1.0 is more like a network Switch or Router, not a traditional enterprise message queue. Compared to a network router that routes packets based on IP or MPLS label, the emqttd broker routes MQTT messages based on topic trie.
  10. .. image:: _static/images/concept.png
  11. Design Philosophy
  12. -----------------
  13. 1. Focus on handling millions of MQTT connections and routing MQTT messages between clustered nodes.
  14. 2. Embrace Erlang/OTP, The Soft-Realtime, Low-Latency, Concurrent and Fault-Tolerant Platform.
  15. 3. Layered Design: Connection, Session, PubSub and Router Layers.
  16. 4. Separate the Message Flow Plane and the Control/Management Plane.
  17. 5. Stream MQTT messages to various backends including MQ or databases.
  18. System Layers
  19. -------------
  20. 1. Connection Layer
  21. Handle TCP and WebSocket connections, encode/decode MQTT packets.
  22. 2. Session Layer
  23. Process MQTT PUBLISH/SUBSCRIBE Packets received from client, and deliver MQTT messages to client.
  24. 3. PubSub Layer
  25. Dispatch MQTT messages to subscribers in a node.
  26. 4. Routing(Distributed) Layer
  27. Route MQTT messages among clustered nodes.
  28. ----------------
  29. Connection Layer
  30. ----------------
  31. This layer is built on the `eSockd`_ library which is a general Non-blocking TCP/SSL Socket Server:
  32. * Acceptor Pool and Asynchronous TCP Accept
  33. * Parameterized Connection Module
  34. * Max connections management
  35. * Allow/Deny by peer address or CIDR
  36. * Keepalive Support
  37. * Rate Limit based on The Leaky Bucket Algorithm
  38. * Fully Asynchronous TCP RECV/SEND
  39. This layer is also responsible for encoding/decoding MQTT frames:
  40. 1. Parse MQTT frames received from client
  41. 2. Serialize MQTT frames sent to client
  42. 3. MQTT Connection Keepalive
  43. Main erlang modules of this layer:
  44. +------------------+--------------------------+
  45. | Module | Description |
  46. +==================+==========================+
  47. | emqttd_client | TCP Client |
  48. +------------------+--------------------------+
  49. | emqttd_ws_client | WebSocket Client |
  50. +------------------+--------------------------+
  51. | emqttd_protocol | MQTT Protocol Handler |
  52. +------------------+--------------------------+
  53. | emqttd_parser | MQTT Frame Parser |
  54. +------------------+--------------------------+
  55. | emqttd_serializer| MQTT Frame Serializer |
  56. +------------------+--------------------------+
  57. -------------
  58. Session Layer
  59. -------------
  60. The session layer processes MQTT packets received from client and delivers PUBLISH packets to client.
  61. A MQTT session will store the subscriptions and inflight messages in memory:
  62. 1. The Client’s subscriptions.
  63. 2. Inflight qos1/2 messages sent to the client but unacked, QoS 2 messages which
  64. have been sent to the Client, but have not been completely acknowledged.
  65. 3. Inflight qos2 messages received from client and waiting for PUBREL. QoS 2
  66. messages which have been received from the Client, but have not been
  67. completely acknowledged.
  68. 4. All qos1, qos2 messages published to when client is disconnected.
  69. MQueue and Inflight Window
  70. --------------------------
  71. Concept of Message Queue and Inflight Window::
  72. |<----------------- Max Len ----------------->|
  73. -----------------------------------------------
  74. IN -> | Messages Queue | Inflight Window | -> Out
  75. -----------------------------------------------
  76. |<--- Win Size --->|
  77. 1. Inflight Window to store the messages delivered and await for PUBACK.
  78. 2. Enqueue messages when the inflight window is full.
  79. 3. If the queue is full, drop qos0 messages if store_qos0 is true, otherwise drop the oldest one.
  80. The larger the inflight window size is, the higher the throughput is. The smaller the window size is, the more strict the message order is.
  81. PacketId and MessageId
  82. ----------------------
  83. The 16-bit PacketId is defined by MQTT Protocol Specification, used by client/server to PUBLISH/PUBACK packets. A GUID(128-bit globally unique Id) will be generated by the broker and assigned to a MQTT message.
  84. Format of the globally unique message id::
  85. --------------------------------------------------------
  86. | Timestamp | NodeID + PID | Sequence |
  87. |<------- 64bits ------->|<--- 48bits --->|<- 16bits ->|
  88. --------------------------------------------------------
  89. 1. Timestamp: erlang:system_time if Erlang >= R18, otherwise os:timestamp
  90. 2. NodeId: encode node() to 2 bytes integer
  91. 3. Pid: encode pid to 4 bytes integer
  92. 4. Sequence: 2 bytes sequence in one process
  93. The PacketId and MessageId in a End-to-End Message PubSub Sequence::
  94. PktId <-- Session --> MsgId <-- Router --> MsgId <-- Session --> PktId
  95. ------------
  96. PubSub Layer
  97. ------------
  98. The PubSub layer maintains a subscription table and is responsible to dispatch MQTT messages to subscribers.
  99. .. image:: _static/images/dispatch.png
  100. MQTT messages will be dispatched to the subscriber's session, which finally delivers the messages to client.
  101. -------------
  102. Routing Layer
  103. -------------
  104. The routing(distributed) layer maintains and replicates the global Topic Trie and Routing Table. The topic tire is composed of wildcard topics created by subscribers. The Routing Table maps a topic to nodes in the cluster.
  105. For example, if node1 subscribed 't/+/x' and 't/+/y', node2 subscribed 't/#' and node3 subscribed 't/a', there will be a topic trie and route table::
  106. -------------------------
  107. | t |
  108. | / \ |
  109. | + # |
  110. | / \ |
  111. | x y |
  112. -------------------------
  113. | t/+/x -> node1, node3 |
  114. | t/+/y -> node1 |
  115. | t/# -> node2 |
  116. | t/a -> node3 |
  117. -------------------------
  118. The routing layer would route MQTT messages among clustered nodes by topic trie match and routing table lookup:
  119. .. image:: _static/images/route.png
  120. The routing design follows two rules:
  121. 1. A message only gets forwarded to other cluster nodes if a cluster node is interested in it. This reduces the network traffic tremendously, because it prevents nodes from forwarding unnecessary messages.
  122. 2. As soon as a client on a node subscribes to a topic it becomes known within the cluster. If one of the clients somewhere in the cluster is publishing to this topic, the message will be delivered to its subscriber no matter to which cluster node it is connected.
  123. .. _design_auth_acl:
  124. ----------------------
  125. Authentication and ACL
  126. ----------------------
  127. The emqttd broker supports an extensible authentication/ACL mechanism, which is implemented by emqttd_access_control, emqttd_auth_mod and emqttd_acl_mod modules.
  128. emqttd_access_control module provides two APIs that help register/unregister auth or ACL module::
  129. register_mod(auth | acl, atom(), list()) -> ok | {error, any()}.
  130. register_mod(auth | acl, atom(), list(), non_neg_integer()) -> ok | {error, any()}.
  131. Authentication Bahaviour
  132. -------------------------
  133. The emqttd_auth_mod defines an Erlang behaviour for authentication module::
  134. -module(emqttd_auth_mod).
  135. -ifdef(use_specs).
  136. -callback init(AuthOpts :: list()) -> {ok, State :: any()}.
  137. -callback check(Client, Password, State) -> ok | ignore | {error, string()} when
  138. Client :: mqtt_client(),
  139. Password :: binary(),
  140. State :: any().
  141. -callback description() -> string().
  142. -else.
  143. -export([behaviour_info/1]).
  144. behaviour_info(callbacks) ->
  145. [{init, 1}, {check, 3}, {description, 0}];
  146. behaviour_info(_Other) ->
  147. undefined.
  148. -endif.
  149. The authentication modules implemented by default:
  150. +-----------------------+--------------------------------+
  151. | Module | Authentication |
  152. +-----------------------+--------------------------------+
  153. | emqttd_auth_username | Username and Password |
  154. +-----------------------+--------------------------------+
  155. | emqttd_auth_clientid | ClientID |
  156. +-----------------------+--------------------------------+
  157. | emqttd_auth_ldap | LDAP |
  158. +-----------------------+--------------------------------+
  159. | emqttd_auth_anonymous | Anonymous |
  160. +-----------------------+--------------------------------+
  161. Authorization(ACL)
  162. ------------------
  163. The emqttd_acl_mod defines an Erlang behavihour for ACL module::
  164. -module(emqttd_acl_mod).
  165. -include("emqttd.hrl").
  166. -ifdef(use_specs).
  167. -callback init(AclOpts :: list()) -> {ok, State :: any()}.
  168. -callback check_acl({Client, PubSub, Topic}, State :: any()) -> allow | deny | ignore when
  169. Client :: mqtt_client(),
  170. PubSub :: pubsub(),
  171. Topic :: binary().
  172. -callback reload_acl(State :: any()) -> ok | {error, any()}.
  173. -callback description() -> string().
  174. -else.
  175. -export([behaviour_info/1]).
  176. behaviour_info(callbacks) ->
  177. [{init, 1}, {check_acl, 2}, {reload_acl, 1}, {description, 0}];
  178. behaviour_info(_Other) ->
  179. undefined.
  180. -endif.
  181. emqttd_acl_internal implements the default ACL based on etc/acl.config file::
  182. %%%-----------------------------------------------------------------------------
  183. %%%
  184. %%% -type who() :: all | binary() |
  185. %%% {ipaddr, esockd_access:cidr()} |
  186. %%% {client, binary()} |
  187. %%% {user, binary()}.
  188. %%%
  189. %%% -type access() :: subscribe | publish | pubsub.
  190. %%%
  191. %%% -type topic() :: binary().
  192. %%%
  193. %%% -type rule() :: {allow, all} |
  194. %%% {allow, who(), access(), list(topic())} |
  195. %%% {deny, all} |
  196. %%% {deny, who(), access(), list(topic())}.
  197. %%%
  198. %%%-----------------------------------------------------------------------------
  199. {allow, {user, "dashboard"}, subscribe, ["$SYS/#"]}.
  200. {allow, {ipaddr, "127.0.0.1"}, pubsub, ["$SYS/#", "#"]}.
  201. {deny, all, subscribe, ["$SYS/#", {eq, "#"}]}.
  202. {allow, all}.
  203. .. _design_hook:
  204. ------------
  205. Hooks Design
  206. ------------
  207. The emqttd broker implements a simple but powerful hooks mechanism to help users develop plugin. The broker would run the hooks when a client is connected/disconnected, a topic is subscribed/unsubscribed or a MQTT message is published/delivered/acked.
  208. Hooks defined by the emqttd 1.0 broker:
  209. +------------------------+------------------------------------------------------+
  210. | Hook | Description |
  211. +========================+======================================================+
  212. | client.connected | Run when client connected to the broker successfully |
  213. +------------------------+------------------------------------------------------+
  214. | client.subscribe | Run before client subscribes topics |
  215. +------------------------+------------------------------------------------------+
  216. | client.subscribe.after | Run After client subscribed topics |
  217. +------------------------+------------------------------------------------------+
  218. | client.unsubscribe | Run when client unsubscribes topics |
  219. +------------------------+------------------------------------------------------+
  220. | message.publish | Run when a MQTT message is published |
  221. +------------------------+------------------------------------------------------+
  222. | message.delivered | Run when a MQTT message is delivered |
  223. +------------------------+------------------------------------------------------+
  224. | message.acked | Run when a MQTT message is acked |
  225. +------------------------+------------------------------------------------------+
  226. | client.disconnected | Run when client disconnected from broker |
  227. +------------------------+------------------------------------------------------+
  228. The emqttd broker uses the `Chain-of-responsibility_pattern`_ to implement hook mechanism. The callback functions registered to hook will be executed one by one::
  229. -------- ok | {ok, NewAcc} -------- ok | {ok, NewAcc} --------
  230. (Args, Acc) --> | Fun1 | -------------------> | Fun2 | -------------------> | Fun3 | --> {ok, Acc} | {stop, Acc}
  231. -------- -------- --------
  232. | | |
  233. stop | {stop, NewAcc} stop | {stop, NewAcc} stop | {stop, NewAcc}
  234. The callback function for a hook should return:
  235. +-----------------+------------------------+
  236. | Return | Description |
  237. +=================+========================+
  238. | ok | Continue |
  239. +-----------------+------------------------+
  240. | {ok, NewAcc} | Return Acc and Continue|
  241. +-----------------+------------------------+
  242. | stop | Break |
  243. +-----------------+------------------------+
  244. | {stop, NewAcc} | Return Acc and Break |
  245. +-----------------+------------------------+
  246. The input arguments for a callback function are depending on the types of hook. Clone the `emqttd_plugin_template`_ project to check the argument in detail.
  247. Hook Implementation
  248. -------------------
  249. The hook APIs defined in emqttd module:
  250. .. code:: erlang
  251. -module(emqttd).
  252. %% Hooks API
  253. -export([hook/4, hook/3, unhook/2, run_hooks/3]).
  254. hook(Hook :: atom(), Callback :: function(), InitArgs :: list(any())) -> ok | {error, any()}.
  255. hook(Hook :: atom(), Callback :: function(), InitArgs :: list(any()), Priority :: integer()) -> ok | {error, any()}.
  256. unhook(Hook :: atom(), Callback :: function()) -> ok | {error, any()}.
  257. run_hooks(Hook :: atom(), Args :: list(any()), Acc :: any()) -> {ok | stop, any()}.
  258. And implemented in emqttd_hook module:
  259. .. code:: erlang
  260. -module(emqttd_hook).
  261. %% Hooks API
  262. -export([add/3, add/4, delete/2, run/3, lookup/1]).
  263. add(HookPoint :: atom(), Callback :: function(), InitArgs :: list(any())) -> ok.
  264. add(HookPoint :: atom(), Callback :: function(), InitArgs :: list(any()), Priority :: integer()) -> ok.
  265. delete(HookPoint :: atom(), Callback :: function()) -> ok.
  266. run(HookPoint :: atom(), Args :: list(any()), Acc :: any()) -> any().
  267. lookup(HookPoint :: atom()) -> [#callback{}].
  268. Hook Usage
  269. ----------
  270. The `emqttd_plugin_template`_ project provides the examples for hook usage:
  271. .. code:: erlang
  272. -module(emqttd_plugin_template).
  273. -export([load/1, unload/0]).
  274. -export([on_message_publish/2, on_message_delivered/3, on_message_acked/3]).
  275. load(Env) ->
  276. emqttd:hook('message.publish', fun ?MODULE:on_message_publish/2, [Env]),
  277. emqttd:hook('message.delivered', fun ?MODULE:on_message_delivered/3, [Env]),
  278. emqttd:hook('message.acked', fun ?MODULE:on_message_acked/3, [Env]).
  279. on_message_publish(Message, _Env) ->
  280. io:format("publish ~s~n", [emqttd_message:format(Message)]),
  281. {ok, Message}.
  282. on_message_delivered(ClientId, Message, _Env) ->
  283. io:format("delivered to client ~s: ~s~n", [ClientId, emqttd_message:format(Message)]),
  284. {ok, Message}.
  285. on_message_acked(ClientId, Message, _Env) ->
  286. io:format("client ~s acked: ~s~n", [ClientId, emqttd_message:format(Message)]),
  287. {ok, Message}.
  288. unload() ->
  289. emqttd:unhook('message.publish', fun ?MODULE:on_message_publish/2),
  290. emqttd:unhook('message.acked', fun ?MODULE:on_message_acked/3),
  291. emqttd:unhook('message.delivered', fun ?MODULE:on_message_delivered/3).
  292. .. _design_plugin:
  293. -------------
  294. Plugin Design
  295. -------------
  296. Plugin is a normal erlang application that can be started/stopped dynamically by a running emqttd broker.
  297. emqttd_plugins Module
  298. ---------------------
  299. The plugin mechanism is implemented by emqttd_plugins module::
  300. -module(emqttd_plugins).
  301. -export([load/1, unload/1]).
  302. %% @doc Load a Plugin
  303. load(PluginName :: atom()) -> ok | {error, any()}.
  304. %% @doc UnLoad a Plugin
  305. unload(PluginName :: atom()) -> ok | {error, any()}.
  306. Load a Plugin
  307. -------------
  308. Use './bin/emqttd_ctl' CLI to load/unload a plugin::
  309. ./bin/emqttd_ctl plugins load emqttd_plugin_redis
  310. ./bin/emqttd_ctl plugins unload emqttd_plugin_redis
  311. Plugin Template
  312. ---------------
  313. http://github.com/emqtt/emqttd_plugin_template
  314. .. _eSockd: https://github.com/emqtt/esockd
  315. .. _Chain-of-responsibility_pattern: https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern
  316. .. _emqttd_plugin_template: https://github.com/emqtt/emqttd_plugin_template/blob/master/src/emqttd_plugin_template.erl