refactor: make Stomp and MQTT-SN gateway as an independent apps

This commit is contained in:
JianBo He 2023-03-29 20:31:58 +08:00
parent 53d760ec69
commit 159bcf329c
31 changed files with 968 additions and 356 deletions

View File

@ -1,97 +1,5 @@
emqx_gateway_schema {
stomp {
desc {
en: """The Stomp Gateway configuration.
This gateway supports v1.2/1.1/1.0"""
zh: """Stomp 网关配置。当前实现支持 v1.2/1.1/1.0 协议版本"""
}
}
stom_frame_max_headers {
desc {
en: """The maximum number of Header"""
zh: """允许的 Header 最大数量"""
}
}
stomp_frame_max_headers_length {
desc {
en: """The maximum string length of the Header Value"""
zh: """允许的 Header 字符串的最大长度"""
}
}
stom_frame_max_body_length {
desc {
en: """Maximum number of bytes of Body allowed per Stomp packet"""
zh: """允许的 Stomp 报文 Body 的最大字节数"""
}
}
mqttsn {
desc {
en: """The MQTT-SN Gateway configuration.
This gateway only supports the v1.2 protocol"""
zh: """MQTT-SN 网关配置。当前实现仅支持 v1.2 版本"""
}
}
mqttsn_gateway_id {
desc {
en: """MQTT-SN Gateway ID.
When the <code>broadcast</code> option is enabled, the gateway will broadcast ADVERTISE message with this value"""
zh: """MQTT-SN 网关 ID。
当 <code>broadcast</code> 打开时MQTT-SN 网关会使用该 ID 来广播 ADVERTISE 消息"""
}
}
mqttsn_broadcast {
desc {
en: """Whether to periodically broadcast ADVERTISE messages"""
zh: """是否周期性广播 ADVERTISE 消息"""
}
}
mqttsn_enable_qos3 {
desc {
en: """Allows connectionless clients to publish messages with a Qos of -1.
This feature is defined for very simple client implementations which do not support any other features except this one. There is no connection setup nor tear down, no registration nor subscription. The client just sends its 'PUBLISH' messages to a GW"""
zh: """是否允许无连接的客户端发送 QoS 等于 -1 的消息。
该功能主要用于支持轻量的 MQTT-SN 客户端实现,它不会向网关建立连接,注册主题,也不会发起订阅;它只使用 QoS 为 -1 来发布消息"""
}
}
mqttsn_subs_resume {
desc {
en: """Whether to initiate all subscribed topic name registration messages to the client after the Session has been taken over by a new channel"""
zh: """在会话被重用后,网关是否主动向客户端注册对已订阅主题名称"""
}
}
mqttsn_predefined {
desc {
en: """The pre-defined topic IDs and topic names.
A 'pre-defined' topic ID is a topic ID whose mapping to a topic name is known in advance by both the client's application and the gateway"""
zh: """预定义主题列表。
预定义的主题列表,是一组 主题 ID 和 主题名称 的映射关系。使用预先定义的主题列表,可以减少 MQTT-SN 客户端和网关对于固定主题的注册请求"""
}
}
mqttsn_predefined_id {
desc {
en: """Topic ID. Range: 1-65535"""
zh: """主题 ID。范围1-65535"""
}
}
mqttsn_predefined_topic {
desc {
en: """Topic Name"""
zh: """主题名称。注:不支持通配符"""
}
}
coap {
desc {
en: """The CoAP Gateway configuration.

View File

@ -395,7 +395,7 @@ fields(Gw) when
Gw == exproto
->
[{name, mk(Gw, #{desc => ?DESC(gateway_name)})}] ++
convert_listener_struct(emqx_gateway_schema:fields(Gw));
convert_listener_struct(emqx_gateway_schema:gateway_schema(Gw));
fields(Gw) when
Gw == update_stomp;
Gw == update_mqttsn;
@ -405,7 +405,7 @@ fields(Gw) when
->
"update_" ++ GwStr = atom_to_list(Gw),
Gw1 = list_to_existing_atom(GwStr),
remove_listener_and_authn(emqx_gateway_schema:fields(Gw1));
remove_listener_and_authn(emqx_gateway_schema:gateway_schema(Gw1));
fields(Listener) when
Listener == tcp_listener;
Listener == ssl_listener;

View File

@ -41,33 +41,49 @@ stop(_State) ->
%% Internal funcs
load_default_gateway_applications() ->
Apps = gateway_type_searching(),
lists:foreach(fun reg/1, Apps).
BuiltInGateways = [
#{
name => lwm2m,
callback_module => emqx_lwm2m_impl,
config_schema_module => emqx_lwm2m_schema
},
#{
name => coap,
callback_module => emqx_coap_impl,
config_schema_module => emqx_gateway_schema
},
#{
name => exproto,
callback_module => emqx_exproto_impl,
config_schema_module => emqx_gateway_schema
}
],
lists:foreach(
fun(Def) ->
load_gateway_application(Def)
end,
emqx_gateway_utils:find_gateway_definations() ++ BuiltInGateways
).
gateway_type_searching() ->
%% FIXME: Hardcoded apps
[
emqx_stomp_impl,
emqx_sn_impl,
emqx_exproto_impl,
emqx_coap_impl,
emqx_lwm2m_impl
].
reg(Mod) ->
try
Mod:reg(),
?SLOG(debug, #{
msg => "register_gateway_succeed",
callback_module => Mod
})
catch
Class:Reason:Stk ->
load_gateway_application(
#{
name := Name,
callback_module := CbMod,
config_schema_module := SchemaMod
}
) ->
RegistryOptions = [{cbkmod, CbMod}, {schema, SchemaMod}],
case emqx_gateway_registry:reg(Name, RegistryOptions) of
ok ->
?SLOG(debug, #{
msg => "register_gateway_succeed",
callback_module => CbMod
});
{error, already_registered} ->
?SLOG(error, #{
msg => "failed_to_register_gateway",
callback_module => Mod,
reason => {Class, Reason},
stacktrace => Stk
msg => "gateway_already_registered",
name => Name,
callback_module => CbMod
})
end.

View File

@ -53,6 +53,8 @@
-export([proxy_protocol_opts/0]).
-export([mountpoint/0, mountpoint/1, gateway_common_options/0, gateway_schema/1]).
namespace() -> gateway.
tags() ->
@ -62,22 +64,6 @@ roots() -> [gateway].
fields(gateway) ->
[
{stomp,
sc(
ref(stomp),
#{
required => {false, recursively},
desc => ?DESC(stomp)
}
)},
{mqttsn,
sc(
ref(mqttsn),
#{
required => {false, recursively},
desc => ?DESC(mqttsn)
}
)},
{coap,
sc(
ref(coap),
@ -102,102 +88,7 @@ fields(gateway) ->
desc => ?DESC(exproto)
}
)}
];
fields(stomp) ->
[
{frame, sc(ref(stomp_frame))},
{mountpoint, mountpoint()},
{listeners, sc(ref(tcp_listeners), #{desc => ?DESC(tcp_listeners)})}
] ++ gateway_common_options();
fields(stomp_frame) ->
[
{max_headers,
sc(
non_neg_integer(),
#{
default => 10,
desc => ?DESC(stom_frame_max_headers)
}
)},
{max_headers_length,
sc(
non_neg_integer(),
#{
default => 1024,
desc => ?DESC(stomp_frame_max_headers_length)
}
)},
{max_body_length,
sc(
integer(),
#{
default => 65536,
desc => ?DESC(stom_frame_max_body_length)
}
)}
];
fields(mqttsn) ->
[
{gateway_id,
sc(
integer(),
#{
default => 1,
required => true,
desc => ?DESC(mqttsn_gateway_id)
}
)},
{broadcast,
sc(
boolean(),
#{
default => false,
desc => ?DESC(mqttsn_broadcast)
}
)},
%% TODO: rename
{enable_qos3,
sc(
boolean(),
#{
default => true,
desc => ?DESC(mqttsn_enable_qos3)
}
)},
{subs_resume,
sc(
boolean(),
#{
default => false,
desc => ?DESC(mqttsn_subs_resume)
}
)},
{predefined,
sc(
hoconsc:array(ref(mqttsn_predefined)),
#{
default => [],
required => {false, recursively},
desc => ?DESC(mqttsn_predefined)
}
)},
{mountpoint, mountpoint()},
{listeners, sc(ref(udp_listeners), #{desc => ?DESC(udp_listeners)})}
] ++ gateway_common_options();
fields(mqttsn_predefined) ->
[
{id,
sc(integer(), #{
required => true,
desc => ?DESC(mqttsn_predefined_id)
})},
{topic,
sc(binary(), #{
required => true,
desc => ?DESC(mqttsn_predefined_topic)
})}
];
] ++ gateway_schemas();
fields(coap) ->
[
{heartbeat,
@ -522,17 +413,6 @@ fields(dtls_opts) ->
desc(gateway) ->
"EMQX Gateway configuration root.";
desc(stomp) ->
"The STOMP protocol gateway provides EMQX with the ability to access STOMP\n"
"(Simple (or Streaming) Text Orientated Messaging Protocol) protocol.";
desc(stomp_frame) ->
"Size limits for the STOMP frames.";
desc(mqttsn) ->
"The MQTT-SN (MQTT for Sensor Networks) protocol gateway.";
desc(mqttsn_predefined) ->
"The pre-defined topic name corresponding to the pre-defined topic\n"
"ID of N.\n\n"
"Note: the pre-defined topic ID of 0 is reserved.";
desc(coap) ->
"The CoAP protocol gateway provides EMQX with the access capability of the CoAP protocol.\n"
"It allows publishing, subscribing, and receiving messages to EMQX in accordance\n"
@ -713,8 +593,33 @@ proxy_protocol_opts() ->
)}
].
sc(Type) ->
sc(Type, #{}).
%%--------------------------------------------------------------------
%% dynamic schemas
%% FIXME: don't hardcode the gateway names
gateway_schema(coap) -> fields(coap);
gateway_schema(lwm2m) -> fields(lwm2m);
gateway_schema(exproto) -> fields(exproto);
gateway_schema(stomp) -> emqx_stomp_schema:fields(stomp);
gateway_schema(mqttsn) -> emqx_mqttsn_schema:fields(mqttsn).
gateway_schemas() ->
lists:map(
fun(#{name := Name, config_schema_module := Mod}) ->
{Name,
sc(
ref(Mod, Name),
#{
required => {false, recursively},
desc => ?DESC(Name)
}
)}
end,
emqx_gateway_utils:find_gateway_definations()
).
%%--------------------------------------------------------------------
%% helpers
sc(Type, Meta) ->
hoconsc:mk(Type, Meta).

View File

@ -46,7 +46,8 @@
global_chain/1,
listener_chain/3,
make_deprecated_paths/1,
make_compatible_schema/2
make_compatible_schema/2,
find_gateway_definations/0
]).
-export([stringfy/1]).
@ -562,3 +563,81 @@ make_compatible_schema2(Path, SchemaFun) ->
end,
Schema
).
find_gateway_definations() ->
lists:flatten(
lists:map(
fun(App) ->
gateways(find_attrs(App, gateway))
end,
ignore_lib_apps(application:loaded_applications())
)
).
gateways([]) ->
[];
gateways([
{_App, _Mod,
Defination =
#{
name := Name,
callback_module := CbMod,
config_schema_module := SchemaMod
}}
| More
]) when is_atom(Name), is_atom(CbMod), is_atom(SchemaMod) ->
[Defination | gateways(More)].
find_attrs(App, Def) ->
[
{App, Mod, Attr}
|| {ok, Modules} <- [application:get_key(App, modules)],
Mod <- Modules,
{Name, Attrs} <- module_attributes(Mod),
Name =:= Def,
Attr <- Attrs
].
module_attributes(Module) ->
try
Module:module_info(attributes)
catch
error:undef -> []
end.
ignore_lib_apps(Apps) ->
LibApps = [
kernel,
stdlib,
sasl,
appmon,
eldap,
erts,
syntax_tools,
ssl,
crypto,
mnesia,
os_mon,
inets,
goldrush,
gproc,
runtime_tools,
snmp,
otp_mibs,
public_key,
asn1,
ssh,
hipe,
common_test,
observer,
webtool,
xmerl,
tools,
test_server,
compiler,
debugger,
eunit,
et,
wx
],
[AppName || {AppName, _, _} <- Apps, not lists:member(AppName, LibApps)].

19
apps/emqx_mqttsn/.gitignore vendored Normal file
View File

@ -0,0 +1,19 @@
.rebar3
_*
.eunit
*.o
*.beam
*.plt
*.swp
*.swo
.erlang.cookie
ebin
log
erl_crash.dump
.rebar
logs
_build
.idea
*.iml
rebar3.crashdump
*~

191
apps/emqx_mqttsn/LICENSE Normal file
View File

@ -0,0 +1,191 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2023, JianBo He <heeejianbo@gmail.com>.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,64 @@
emqx_mqttsn_schema {
mqttsn {
desc {
en: """The MQTT-SN Gateway configuration.
This gateway only supports the v1.2 protocol"""
zh: """MQTT-SN 网关配置。当前实现仅支持 v1.2 版本"""
}
}
mqttsn_gateway_id {
desc {
en: """MQTT-SN Gateway ID.
When the <code>broadcast</code> option is enabled, the gateway will broadcast ADVERTISE message with this value"""
zh: """MQTT-SN 网关 ID。
当 <code>broadcast</code> 打开时MQTT-SN 网关会使用该 ID 来广播 ADVERTISE 消息"""
}
}
mqttsn_broadcast {
desc {
en: """Whether to periodically broadcast ADVERTISE messages"""
zh: """是否周期性广播 ADVERTISE 消息"""
}
}
mqttsn_enable_qos3 {
desc {
en: """Allows connectionless clients to publish messages with a Qos of -1.
This feature is defined for very simple client implementations which do not support any other features except this one. There is no connection setup nor tear down, no registration nor subscription. The client just sends its 'PUBLISH' messages to a GW"""
zh: """是否允许无连接的客户端发送 QoS 等于 -1 的消息。
该功能主要用于支持轻量的 MQTT-SN 客户端实现,它不会向网关建立连接,注册主题,也不会发起订阅;它只使用 QoS 为 -1 来发布消息"""
}
}
mqttsn_subs_resume {
desc {
en: """Whether to initiate all subscribed topic name registration messages to the client after the Session has been taken over by a new channel"""
zh: """在会话被重用后,网关是否主动向客户端注册对已订阅主题名称"""
}
}
mqttsn_predefined {
desc {
en: """The pre-defined topic IDs and topic names.
A 'pre-defined' topic ID is a topic ID whose mapping to a topic name is known in advance by both the client's application and the gateway"""
zh: """预定义主题列表。
预定义的主题列表,是一组 主题 ID 和 主题名称 的映射关系。使用预先定义的主题列表,可以减少 MQTT-SN 客户端和网关对于固定主题的注册请求"""
}
}
mqttsn_predefined_id {
desc {
en: """Topic ID. Range: 1-65535"""
zh: """主题 ID。范围1-65535"""
}
}
mqttsn_predefined_topic {
desc {
en: """Topic Name"""
zh: """主题名称。注:不支持通配符"""
}
}
}

View File

@ -0,0 +1,2 @@
{erl_opts, [debug_info]}.
{deps, []}.

View File

@ -0,0 +1,10 @@
{application, emqx_mqttsn,
[{description, "MQTT-SN Gateway"},
{vsn, "0.1.0"},
{registered, []},
{applications, [kernel, stdlib]},
{env,[]},
{modules, []},
{licenses, ["Apache 2.0"]},
{links, []}
]}.

View File

@ -1,5 +1,5 @@
%%--------------------------------------------------------------------
%% Copyright (c) 2021-2023 EMQ Technologies Co., Ltd. All Rights Reserved.
%% Copyright (c) 2021 EMQ Technologies Co., Ltd. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
@ -14,13 +14,28 @@
%% limitations under the License.
%%--------------------------------------------------------------------
%% @doc The MQTT-SN Gateway Implement interface
-module(emqx_sn_impl).
-behaviour(emqx_gateway_impl).
%% @doc The MQTT-SN Gateway implement interface
-module(emqx_mqttsn).
-include_lib("emqx/include/logger.hrl").
%% define a gateway named stomp
-gateway(#{
name => mqttsn,
callback_module => ?MODULE,
config_schema_module => emqx_mqttsn_schema
}).
%% callback_module must implement the emqx_gateway_impl behaviour
-behaviour(emqx_gateway_impl).
%% callback for emqx_gateway_impl
-export([
on_gateway_load/2,
on_gateway_update/3,
on_gateway_unload/2
]).
-import(
emqx_gateway_utils,
[
@ -30,31 +45,8 @@
]
).
%% APIs
-export([
reg/0,
unreg/0
]).
-export([
on_gateway_load/2,
on_gateway_update/3,
on_gateway_unload/2
]).
%%--------------------------------------------------------------------
%% APIs
%%--------------------------------------------------------------------
reg() ->
RegistryOptions = [{cbkmod, ?MODULE}],
emqx_gateway_registry:reg(mqttsn, RegistryOptions).
unreg() ->
emqx_gateway_registry:unreg(mqttsn).
%%--------------------------------------------------------------------
%% emqx_gateway_registry callbacks
%% emqx_gateway_impl callbacks
%%--------------------------------------------------------------------
on_gateway_load(
@ -64,8 +56,8 @@ on_gateway_load(
},
Ctx
) ->
%% We Also need to start `emqx_sn_broadcast` &
%% `emqx_sn_registry` process
%% We Also need to start `emqx_mqttsn_broadcast` &
%% `emqx_mqttsn_registry` process
case maps:get(broadcast, Config, false) of
false ->
ok;
@ -73,23 +65,23 @@ on_gateway_load(
%% FIXME:
Port = 1884,
SnGwId = maps:get(gateway_id, Config, undefined),
_ = emqx_sn_broadcast:start_link(SnGwId, Port),
_ = emqx_mqttsn_broadcast:start_link(SnGwId, Port),
ok
end,
PredefTopics = maps:get(predefined, Config, []),
{ok, RegistrySvr} = emqx_sn_registry:start_link(GwName, PredefTopics),
{ok, RegistrySvr} = emqx_mqttsn_registry:start_link(GwName, PredefTopics),
NConfig = maps:without(
[broadcast, predefined],
Config#{registry => emqx_sn_registry:lookup_name(RegistrySvr)}
Config#{registry => emqx_mqttsn_registry:lookup_name(RegistrySvr)}
),
Listeners = emqx_gateway_utils:normalize_config(NConfig),
ModCfg = #{
frame_mod => emqx_sn_frame,
chann_mod => emqx_sn_channel
frame_mod => emqx_mqttsn_frame,
chann_mod => emqx_mqttsn_channel
},
case

View File

@ -14,17 +14,11 @@
%% limitations under the License.
%%--------------------------------------------------------------------
-module(emqx_sn_broadcast).
-module(emqx_mqttsn_broadcast).
-behaviour(gen_server).
-ifdef(TEST).
%% make rebar3 ct happy when testing with --suite path/to/module_SUITE.erl
-include_lib("emqx_gateway/src/mqttsn/include/emqx_sn.hrl").
-else.
%% make mix happy
-include("src/mqttsn/include/emqx_sn.hrl").
-endif.
-include("emqx_mqttsn.hrl").
-include_lib("emqx/include/logger.hrl").
-export([
@ -65,7 +59,7 @@ stop() ->
init([GwId, Port]) ->
%% FIXME:
Duration = application:get_env(emqx_sn, advertise_duration, ?DEFAULT_DURATION),
Duration = application:get_env(emqx_mqttsn, advertise_duration, ?DEFAULT_DURATION),
{ok, Sock} = gen_udp:open(0, [binary, {broadcast, true}]),
{ok,
ensure_advertise(#state{
@ -121,7 +115,7 @@ send_advertise(#state{
addrs = Addrs,
duration = Duration
}) ->
Data = emqx_sn_frame:serialize_pkt(?SN_ADVERTISE_MSG(GwId, Duration), #{}),
Data = emqx_mqttsn_frame:serialize_pkt(?SN_ADVERTISE_MSG(GwId, Duration), #{}),
lists:foreach(
fun(Addr) ->
?SLOG(debug, #{

View File

@ -14,11 +14,11 @@
%% limitations under the License.
%%--------------------------------------------------------------------
-module(emqx_sn_channel).
-module(emqx_mqttsn_channel).
-behaviour(emqx_gateway_channel).
-include("src/mqttsn/include/emqx_sn.hrl").
-include("emqx_mqttsn.hrl").
-include_lib("emqx/include/emqx.hrl").
-include_lib("emqx/include/types.hrl").
-include_lib("emqx/include/emqx_mqtt.hrl").
@ -51,7 +51,7 @@
%% Context
ctx :: emqx_gateway_ctx:context(),
%% Registry
registry :: emqx_sn_registry:registry(),
registry :: emqx_mqttsn_registry:registry(),
%% Gateway Id
gateway_id :: integer(),
%% Enable QoS3
@ -478,7 +478,7 @@ handle_in(
true ->
<<TopicId:16>>;
false ->
emqx_sn_registry:lookup_topic(
emqx_mqttsn_registry:lookup_topic(
Registry,
?NEG_QOS_CLIENT_ID,
TopicId
@ -624,7 +624,7 @@ handle_in(
clientinfo = #{clientid := ClientId}
}
) ->
case emqx_sn_registry:register_topic(Registry, ClientId, TopicName) of
case emqx_mqttsn_registry:register_topic(Registry, ClientId, TopicName) of
TopicId when is_integer(TopicId) ->
?SLOG(debug, #{
msg => "registered_topic_name",
@ -778,7 +778,7 @@ handle_in(
{ok, Channel}
end;
?SN_RC_INVALID_TOPIC_ID ->
case emqx_sn_registry:lookup_topic(Registry, ClientId, TopicId) of
case emqx_mqttsn_registry:lookup_topic(Registry, ClientId, TopicId) of
undefined ->
{ok, Channel};
TopicName ->
@ -1093,7 +1093,7 @@ convert_topic_id_to_name(
clientinfo = #{clientid := ClientId}
}
) ->
case emqx_sn_registry:lookup_topic(Registry, ClientId, TopicId) of
case emqx_mqttsn_registry:lookup_topic(Registry, ClientId, TopicId) of
undefined ->
{error, ?SN_RC_INVALID_TOPIC_ID};
TopicName ->
@ -1202,7 +1202,7 @@ preproc_subs_type(
%% If the gateway is able accept the subscription,
%% it assigns a topic id to the received topic name
%% and returns it within a SUBACK message
case emqx_sn_registry:register_topic(Registry, ClientId, TopicName) of
case emqx_mqttsn_registry:register_topic(Registry, ClientId, TopicName) of
{error, too_large} ->
{error, ?SN_RC2_EXCEED_LIMITATION};
{error, wildcard_topic} ->
@ -1228,7 +1228,7 @@ preproc_subs_type(
}
) ->
case
emqx_sn_registry:lookup_topic(
emqx_mqttsn_registry:lookup_topic(
Registry,
ClientId,
TopicId
@ -1344,7 +1344,7 @@ preproc_unsub_type(
}
) ->
case
emqx_sn_registry:lookup_topic(
emqx_mqttsn_registry:lookup_topic(
Registry,
ClientId,
TopicId
@ -1765,7 +1765,7 @@ message_to_packet(
?QOS_0 -> 0;
_ -> MsgId
end,
case emqx_sn_registry:lookup_topic_id(Registry, ClientId, Topic) of
case emqx_mqttsn_registry:lookup_topic_id(Registry, ClientId, Topic) of
{predef, PredefTopicId} ->
Flags = #mqtt_sn_flags{qos = QoS, topic_id_type = ?SN_PREDEFINED_TOPIC},
?SN_PUBLISH_MSG(Flags, PredefTopicId, NMsgId, Payload);
@ -1932,9 +1932,9 @@ ensure_registered_topic_name(
Channel = #channel{registry = Registry}
) ->
ClientId = clientid(Channel),
case emqx_sn_registry:lookup_topic_id(Registry, ClientId, TopicName) of
case emqx_mqttsn_registry:lookup_topic_id(Registry, ClientId, TopicName) of
undefined ->
case emqx_sn_registry:register_topic(Registry, ClientId, TopicName) of
case emqx_mqttsn_registry:register_topic(Registry, ClientId, TopicName) of
{error, Reason} -> {error, Reason};
TopicId -> {ok, TopicId}
end;

View File

@ -16,11 +16,11 @@
%%--------------------------------------------------------------------
%% @doc The frame parser for MQTT-SN protocol
-module(emqx_sn_frame).
-module(emqx_mqttsn_frame).
-behaviour(emqx_gateway_frame).
-include("src/mqttsn/include/emqx_sn.hrl").
-include("emqx_mqttsn.hrl").
-export([
initial_parse_state/1,
@ -438,7 +438,7 @@ format(?SN_DISCONNECT_MSG(Duration)) ->
format(#mqtt_sn_message{type = Type, variable = Var}) ->
io_lib:format(
"mqtt_sn_message(type=~s, Var=~w)",
[emqx_sn_frame:message_type(Type), Var]
[emqx_mqttsn_frame:message_type(Type), Var]
).
is_message(#mqtt_sn_message{type = Type}) when

View File

@ -15,13 +15,11 @@
%%--------------------------------------------------------------------
%% @doc The MQTT-SN Topic Registry
%%
%% XXX:
-module(emqx_sn_registry).
-module(emqx_mqttsn_registry).
-behaviour(gen_server).
-include("src/mqttsn/include/emqx_sn.hrl").
-include("emqx_mqttsn.hrl").
-include_lib("emqx/include/logger.hrl").
-export([start_link/2]).
@ -53,11 +51,11 @@
-export([lookup_name/1]).
-define(SN_SHARD, emqx_sn_shard).
-define(SN_SHARD, emqx_mqttsn_shard).
-record(state, {tabname, max_predef_topic_id = 0}).
-record(emqx_sn_registry, {key, value}).
-record(emqx_mqttsn_registry, {key, value}).
-type registry() :: {Tab :: atom(), RegistryPid :: pid()}.
@ -126,7 +124,7 @@ lookup_name(Pid) ->
%%-----------------------------------------------------------------------------
name(InstaId) ->
list_to_atom(lists:concat([emqx_sn_, InstaId, '_registry'])).
list_to_atom(lists:concat([emqx_mqttsn_, InstaId, '_registry'])).
init([InstaId, PredefTopics]) ->
%% {predef, TopicId} -> TopicName
@ -136,8 +134,8 @@ init([InstaId, PredefTopics]) ->
Tab = name(InstaId),
ok = mria:create_table(Tab, [
{storage, ram_copies},
{record_name, emqx_sn_registry},
{attributes, record_info(fields, emqx_sn_registry)},
{record_name, emqx_mqttsn_registry},
{attributes, record_info(fields, emqx_mqttsn_registry)},
{storage_properties, [{ets, [{read_concurrency, true}]}]},
{rlog_shard, ?SN_SHARD}
]),
@ -145,11 +143,11 @@ init([InstaId, PredefTopics]) ->
MaxPredefId = lists:foldl(
fun(#{id := TopicId, topic := TopicName0}, AccId) ->
TopicName = iolist_to_binary(TopicName0),
mria:dirty_write(Tab, #emqx_sn_registry{
mria:dirty_write(Tab, #emqx_mqttsn_registry{
key = {predef, TopicId},
value = TopicName
}),
mria:dirty_write(Tab, #emqx_sn_registry{
mria:dirty_write(Tab, #emqx_mqttsn_registry{
key = {predef, TopicName},
value = TopicId
}),
@ -193,7 +191,7 @@ handle_call(
handle_call({unregister, ClientId}, _From, State = #state{tabname = Tab}) ->
Registry = mnesia:dirty_match_object(
Tab,
{emqx_sn_registry, {ClientId, '_'}, '_'}
{emqx_mqttsn_registry, {ClientId, '_'}, '_'}
),
lists:foreach(
fun(R) ->
@ -234,7 +232,7 @@ code_change(_OldVsn, State, _Extra) ->
do_register(Tab, ClientId, TopicId, TopicName) ->
mnesia:write(
Tab,
#emqx_sn_registry{
#emqx_mqttsn_registry{
key = {ClientId, next_topic_id},
value = TopicId + 1
},
@ -242,7 +240,7 @@ do_register(Tab, ClientId, TopicId, TopicName) ->
),
mnesia:write(
Tab,
#emqx_sn_registry{
#emqx_mqttsn_registry{
key = {ClientId, TopicName},
value = TopicId
},
@ -250,7 +248,7 @@ do_register(Tab, ClientId, TopicId, TopicName) ->
),
mnesia:write(
Tab,
#emqx_sn_registry{
#emqx_mqttsn_registry{
key = {ClientId, TopicId},
value = TopicName
},
@ -261,6 +259,6 @@ do_register(Tab, ClientId, TopicId, TopicName) ->
next_topic_id(Tab, PredefId, ClientId) ->
case mnesia:dirty_read(Tab, {ClientId, next_topic_id}) of
[#emqx_sn_registry{value = Id}] -> Id;
[#emqx_mqttsn_registry{value = Id}] -> Id;
[] -> PredefId + 1
end.

View File

@ -0,0 +1,107 @@
%%--------------------------------------------------------------------
%% Copyright (c) 2023 EMQ Technologies Co., Ltd. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
-module(emqx_mqttsn_schema).
-include_lib("hocon/include/hoconsc.hrl").
-include_lib("typerefl/include/types.hrl").
%% config schema provides
-export([fields/1, desc/1]).
fields(mqttsn) ->
[
{gateway_id,
sc(
integer(),
#{
default => 1,
required => true,
desc => ?DESC(mqttsn_gateway_id)
}
)},
{broadcast,
sc(
boolean(),
#{
default => false,
desc => ?DESC(mqttsn_broadcast)
}
)},
%% TODO: rename
{enable_qos3,
sc(
boolean(),
#{
default => true,
desc => ?DESC(mqttsn_enable_qos3)
}
)},
{subs_resume,
sc(
boolean(),
#{
default => false,
desc => ?DESC(mqttsn_subs_resume)
}
)},
{predefined,
sc(
hoconsc:array(ref(mqttsn_predefined)),
#{
default => [],
required => {false, recursively},
desc => ?DESC(mqttsn_predefined)
}
)},
{mountpoint, emqx_gateway_schema:mountpoint()},
{listeners, sc(ref(emqx_gateway_schema, udp_listeners), #{desc => ?DESC(udp_listeners)})}
] ++ emqx_gateway_schema:gateway_common_options();
fields(mqttsn_predefined) ->
[
{id,
sc(integer(), #{
required => true,
desc => ?DESC(mqttsn_predefined_id)
})},
{topic,
sc(binary(), #{
required => true,
desc => ?DESC(mqttsn_predefined_topic)
})}
].
desc(mqttsn) ->
"The MQTT-SN (MQTT for Sensor Networks) protocol gateway.";
desc(mqttsn_predefined) ->
"The pre-defined topic name corresponding to the pre-defined topic\n"
"ID of N.\n\n"
"Note: the pre-defined topic ID of 0 is reserved.";
desc(_) ->
undefined.
%%--------------------------------------------------------------------
%% internal functions
sc(Type, Meta) ->
hoconsc:mk(Type, Meta).
ref(StructName) ->
ref(?MODULE, StructName).
ref(Mod, Field) ->
hoconsc:ref(Mod, Field).

19
apps/emqx_stomp/.gitignore vendored Normal file
View File

@ -0,0 +1,19 @@
.rebar3
_*
.eunit
*.o
*.beam
*.plt
*.swp
*.swo
.erlang.cookie
ebin
log
erl_crash.dump
.rebar
logs
_build
.idea
*.iml
rebar3.crashdump
*~

191
apps/emqx_stomp/LICENSE Normal file
View File

@ -0,0 +1,191 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2023, JianBo He <heeejianbo@gmail.com>.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,32 @@
emqx_stomp_schema {
stomp {
desc {
en: """The Stomp Gateway configuration.
This gateway supports v1.2/1.1/1.0"""
zh: """Stomp 网关配置。当前实现支持 v1.2/1.1/1.0 协议版本"""
}
}
stom_frame_max_headers {
desc {
en: """The maximum number of Header"""
zh: """允许的 Header 最大数量"""
}
}
stomp_frame_max_headers_length {
desc {
en: """The maximum string length of the Header Value"""
zh: """允许的 Header 字符串的最大长度"""
}
}
stom_frame_max_body_length {
desc {
en: """Maximum number of bytes of Body allowed per Stomp packet"""
zh: """允许的 Stomp 报文 Body 的最大字节数"""
}
}
}

View File

@ -0,0 +1,2 @@
{erl_opts, [debug_info]}.
{deps, []}.

View File

@ -0,0 +1,10 @@
{application, emqx_stomp, [
{description, "Stomp gateway"},
{vsn, "0.1.0"},
{registered, []},
{applications, [kernel, stdlib]},
{env, []},
{modules, []},
{licenses, ["Apache 2.0"]},
{links, []}
]}.

View File

@ -1,5 +1,5 @@
%%--------------------------------------------------------------------
%% Copyright (c) 2017-2023 EMQ Technologies Co., Ltd. All Rights Reserved.
%% Copyright (c) 2021 EMQ Technologies Co., Ltd. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
@ -14,13 +14,29 @@
%% limitations under the License.
%%--------------------------------------------------------------------
-module(emqx_stomp_impl).
-behaviour(emqx_gateway_impl).
%% @doc The Stomp Gateway implement interface
-module(emqx_stomp).
-include_lib("emqx/include/logger.hrl").
-include_lib("emqx_gateway/include/emqx_gateway.hrl").
%% define a gateway named stomp
-gateway(#{
name => stomp,
callback_module => ?MODULE,
config_schema_module => emqx_stomp_schema
}).
%% callback_module must implement the emqx_gateway_impl behaviour
-behaviour(emqx_gateway_impl).
%% callback for emqx_gateway_impl
-export([
on_gateway_load/2,
on_gateway_update/3,
on_gateway_unload/2
]).
-import(
emqx_gateway_utils,
[
@ -30,33 +46,8 @@
]
).
%% APIs
-export([
reg/0,
unreg/0
]).
-export([
on_gateway_load/2,
on_gateway_update/3,
on_gateway_unload/2
]).
%%--------------------------------------------------------------------
%% APIs
%%--------------------------------------------------------------------
-spec reg() -> ok | {error, any()}.
reg() ->
RegistryOptions = [{cbkmod, ?MODULE}],
emqx_gateway_registry:reg(stomp, RegistryOptions).
-spec unreg() -> ok | {error, any()}.
unreg() ->
emqx_gateway_registry:unreg(stomp).
%%--------------------------------------------------------------------
%% emqx_gateway_registry callbacks
%% emqx_gateway_impl callbacks
%%--------------------------------------------------------------------
on_gateway_load(

View File

@ -18,7 +18,7 @@
-behaviour(emqx_gateway_channel).
-include("src/stomp/include/emqx_stomp.hrl").
-include("emqx_stomp.hrl").
-include_lib("emqx/include/emqx.hrl").
-include_lib("emqx/include/logger.hrl").

View File

@ -70,7 +70,7 @@
-behaviour(emqx_gateway_frame).
-include("src/stomp/include/emqx_stomp.hrl").
-include("emqx_stomp.hrl").
-export([
initial_parse_state/1,

View File

@ -17,7 +17,7 @@
%% @doc Stomp heartbeat.
-module(emqx_stomp_heartbeat).
-include("src/stomp/include/emqx_stomp.hrl").
-include("emqx_stomp.hrl").
-export([
init/1,

View File

@ -0,0 +1,80 @@
%%--------------------------------------------------------------------
%% Copyright (c) 2023 EMQ Technologies Co., Ltd. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
-module(emqx_stomp_schema).
-include_lib("hocon/include/hoconsc.hrl").
-include_lib("typerefl/include/types.hrl").
%% config schema provides
-export([fields/1, desc/1]).
fields(stomp) ->
[
{frame, sc(ref(stomp_frame))},
{mountpoint, emqx_gateway_schema:mountpoint()},
{listeners, sc(ref(emqx_gateway_schema, tcp_listeners), #{desc => ?DESC(tcp_listeners)})}
] ++ emqx_gateway_schema:gateway_common_options();
fields(stomp_frame) ->
[
{max_headers,
sc(
non_neg_integer(),
#{
default => 10,
desc => ?DESC(stom_frame_max_headers)
}
)},
{max_headers_length,
sc(
non_neg_integer(),
#{
default => 1024,
desc => ?DESC(stomp_frame_max_headers_length)
}
)},
{max_body_length,
sc(
integer(),
#{
default => 65536,
desc => ?DESC(stom_frame_max_body_length)
}
)}
].
desc(stomp) ->
"The STOMP protocol gateway provides EMQX with the ability to access STOMP\n"
"(Simple (or Streaming) Text Orientated Messaging Protocol) protocol.";
desc(stomp_frame) ->
"Size limits for the STOMP frames.";
desc(_) ->
undefined.
%%--------------------------------------------------------------------
%% internal functions
sc(Type) ->
sc(Type, #{}).
sc(Type, Meta) ->
hoconsc:mk(Type, Meta).
ref(StructName) ->
ref(?MODULE, StructName).
ref(Mod, Field) ->
hoconsc:ref(Mod, Field).

View File

@ -389,6 +389,8 @@ relx_apps(ReleaseType, Edition) ->
emqx_authz,
emqx_auto_subscribe,
emqx_gateway,
emqx_stomp,
emqx_mqttsn,
emqx_exhook,
emqx_bridge,
emqx_rule_engine,