emqx_bridge_tdengine_SUITE.erl 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2022-2024 EMQ Technologies Co., Ltd. All Rights Reserved.
  3. %%--------------------------------------------------------------------
  4. -module(emqx_bridge_tdengine_SUITE).
  5. -compile(nowarn_export_all).
  6. -compile(export_all).
  7. -include_lib("eunit/include/eunit.hrl").
  8. -include_lib("common_test/include/ct.hrl").
  9. -include_lib("snabbkaffe/include/snabbkaffe.hrl").
  10. % SQL definitions
  11. -define(SQL_BRIDGE,
  12. "insert into t_mqtt_msg(ts, payload) values (${timestamp}, '${payload}')"
  13. "t_mqtt_msg(ts, payload) values (${second_ts}, '${payload}')"
  14. ).
  15. -define(SQL_CREATE_DATABASE, "CREATE DATABASE IF NOT EXISTS mqtt; USE mqtt;").
  16. -define(SQL_CREATE_TABLE,
  17. "CREATE TABLE t_mqtt_msg (\n"
  18. " ts timestamp,\n"
  19. " payload BINARY(1024)\n"
  20. ");"
  21. ).
  22. -define(SQL_DROP_TABLE, "DROP TABLE t_mqtt_msg").
  23. -define(SQL_DROP_STABLE, "DROP STABLE s_tab").
  24. -define(SQL_DELETE, "DELETE FROM t_mqtt_msg").
  25. -define(SQL_SELECT, "SELECT payload FROM t_mqtt_msg").
  26. -define(AUTO_CREATE_BRIDGE,
  27. "insert into ${clientid} USING s_tab TAGS ('${clientid}') values (${timestamp}, '${payload}')"
  28. "test_${clientid} USING s_tab TAGS ('${clientid}') values (${second_ts}, '${payload}')"
  29. ).
  30. -define(SQL_CREATE_STABLE,
  31. "CREATE STABLE s_tab (\n"
  32. " ts timestamp,\n"
  33. " payload BINARY(1024)\n"
  34. ") TAGS (clientid BINARY(128));"
  35. ).
  36. % DB defaults
  37. -define(TD_DATABASE, "mqtt").
  38. -define(TD_USERNAME, "root").
  39. -define(TD_PASSWORD, "taosdata").
  40. -define(BATCH_SIZE, 10).
  41. -define(PAYLOAD, <<"HELLO">>).
  42. -define(WITH_CON(Process),
  43. Con = connect_direct_tdengine(Config),
  44. Process,
  45. ok = tdengine:stop(Con)
  46. ).
  47. -define(BRIDGE_TYPE_BIN, <<"tdengine">>).
  48. -define(APPS, [
  49. hackney, tdengine, emqx_bridge, emqx_resource, emqx_rule_engine, emqx_bridge_tdengine
  50. ]).
  51. %%------------------------------------------------------------------------------
  52. %% CT boilerplate
  53. %%------------------------------------------------------------------------------
  54. all() ->
  55. [
  56. {group, async},
  57. {group, sync}
  58. ].
  59. groups() ->
  60. TCs = emqx_common_test_helpers:all(?MODULE),
  61. MustBatchCases = [t_batch_insert, t_auto_create_batch_insert],
  62. BatchingGroups = [{group, with_batch}, {group, without_batch}],
  63. [
  64. {async, BatchingGroups},
  65. {sync, BatchingGroups},
  66. {with_batch, TCs},
  67. {without_batch, TCs -- MustBatchCases}
  68. ].
  69. init_per_suite(Config) ->
  70. emqx_bridge_v2_testlib:init_per_suite(Config, ?APPS).
  71. end_per_suite(Config) ->
  72. emqx_bridge_v2_testlib:end_per_suite(Config).
  73. init_per_group(async, Config) ->
  74. [{query_mode, async} | Config];
  75. init_per_group(sync, Config) ->
  76. [{query_mode, sync} | Config];
  77. init_per_group(with_batch, Config0) ->
  78. Config = [{enable_batch, true} | Config0],
  79. common_init(Config);
  80. init_per_group(without_batch, Config0) ->
  81. Config = [{enable_batch, false} | Config0],
  82. common_init(Config);
  83. init_per_group(_Group, Config) ->
  84. Config.
  85. end_per_group(default, Config) ->
  86. emqx_bridge_v2_testlib:end_per_group(Config),
  87. ok;
  88. end_per_group(_Group, _Config) ->
  89. ok.
  90. init_per_testcase(TestCase, Config0) ->
  91. connect_and_clear_table(Config0),
  92. Type = ?config(bridge_type, Config0),
  93. UniqueNum = integer_to_binary(erlang:unique_integer()),
  94. Name = <<
  95. (atom_to_binary(TestCase))/binary, UniqueNum/binary
  96. >>,
  97. {_ConfigString, ConnectorConfig} = connector_config(Name, Config0),
  98. {_, ActionConfig} = action_config(TestCase, Name, Config0),
  99. Config = [
  100. {connector_type, Type},
  101. {connector_name, Name},
  102. {connector_config, ConnectorConfig},
  103. {bridge_type, Type},
  104. {bridge_name, Name},
  105. {bridge_config, ActionConfig}
  106. | Config0
  107. ],
  108. emqx_bridge_v2_testlib:delete_all_bridges_and_connectors(),
  109. ok = snabbkaffe:start_trace(),
  110. Config.
  111. end_per_testcase(TestCase, Config) ->
  112. emqx_bridge_v2_testlib:end_per_testcase(TestCase, Config),
  113. connect_and_clear_table(Config),
  114. ok.
  115. %%------------------------------------------------------------------------------
  116. %% Helper fns
  117. %%------------------------------------------------------------------------------
  118. common_init(ConfigT) ->
  119. Host = os:getenv("TDENGINE_HOST", "toxiproxy"),
  120. Port = list_to_integer(os:getenv("TDENGINE_PORT", "6041")),
  121. Config0 = [
  122. {td_host, Host},
  123. {td_port, Port},
  124. {proxy_name, "tdengine_restful"}
  125. | ConfigT
  126. ],
  127. case emqx_common_test_helpers:is_tcp_server_available(Host, Port) of
  128. true ->
  129. Config = emqx_bridge_v2_testlib:init_per_group(default, ?BRIDGE_TYPE_BIN, Config0),
  130. connect_and_create_table(Config),
  131. Config;
  132. false ->
  133. case os:getenv("IS_CI") of
  134. "yes" ->
  135. throw(no_tdengine);
  136. _ ->
  137. {skip, no_tdengine}
  138. end
  139. end.
  140. action_config(TestCase, Name, Config) ->
  141. Type = ?config(bridge_type, Config),
  142. BatchSize =
  143. case ?config(enable_batch, Config) of
  144. true -> ?BATCH_SIZE;
  145. false -> 1
  146. end,
  147. QueryMode = ?config(query_mode, Config),
  148. ConfigString =
  149. io_lib:format(
  150. "actions.~s.~s {\n"
  151. " enable = true\n"
  152. " connector = \"~s\"\n"
  153. " parameters = {\n"
  154. " database = ~p\n"
  155. " sql = ~p\n"
  156. " }\n"
  157. " resource_opts = {\n"
  158. " request_ttl = 500ms\n"
  159. " batch_size = ~b\n"
  160. " query_mode = ~s\n"
  161. " }\n"
  162. "}\n",
  163. [
  164. Type,
  165. Name,
  166. Name,
  167. ?TD_DATABASE,
  168. case TestCase of
  169. Auto when
  170. Auto =:= t_auto_create_simple_insert; Auto =:= t_auto_create_batch_insert
  171. ->
  172. ?AUTO_CREATE_BRIDGE;
  173. _ ->
  174. ?SQL_BRIDGE
  175. end,
  176. BatchSize,
  177. QueryMode
  178. ]
  179. ),
  180. ct:pal("ActionConfig:~ts~n", [ConfigString]),
  181. {ConfigString, parse_action_and_check(ConfigString, Type, Name)}.
  182. connector_config(Name, Config) ->
  183. Host = ?config(td_host, Config),
  184. Port = ?config(td_port, Config),
  185. Type = ?config(bridge_type, Config),
  186. Server = Host ++ ":" ++ integer_to_list(Port),
  187. ConfigString =
  188. io_lib:format(
  189. "connectors.~s.~s {\n"
  190. " enable = true\n"
  191. " server = \"~s\"\n"
  192. " username = ~p\n"
  193. " password = ~p\n"
  194. "}\n",
  195. [
  196. Type,
  197. Name,
  198. Server,
  199. ?TD_USERNAME,
  200. ?TD_PASSWORD
  201. ]
  202. ),
  203. ct:pal("ConnectorConfig:~ts~n", [ConfigString]),
  204. {ConfigString, parse_connector_and_check(ConfigString, Type, Name)}.
  205. parse_action_and_check(ConfigString, BridgeType, Name) ->
  206. parse_and_check(ConfigString, emqx_bridge_schema, <<"actions">>, BridgeType, Name).
  207. parse_connector_and_check(ConfigString, ConnectorType, Name) ->
  208. parse_and_check(
  209. ConfigString, emqx_connector_schema, <<"connectors">>, ConnectorType, Name
  210. ).
  211. parse_and_check(ConfigString, SchemaMod, RootKey, Type0, Name) ->
  212. Type = to_bin(Type0),
  213. {ok, RawConf} = hocon:binary(ConfigString, #{format => map}),
  214. hocon_tconf:check_plain(SchemaMod, RawConf, #{required => false, atom_key => false}),
  215. #{RootKey := #{Type := #{Name := Config}}} = RawConf,
  216. Config.
  217. to_bin(List) when is_list(List) ->
  218. unicode:characters_to_binary(List, utf8);
  219. to_bin(Atom) when is_atom(Atom) ->
  220. erlang:atom_to_binary(Atom);
  221. to_bin(Bin) when is_binary(Bin) ->
  222. Bin.
  223. send_message(Config, Payload) ->
  224. BridgeType = ?config(bridge_type, Config),
  225. Name = ?config(bridge_name, Config),
  226. ct:print(">>> Name:~p~n BridgeType:~p~n", [Name, BridgeType]),
  227. emqx_bridge_v2:send_message(BridgeType, Name, Payload, #{}).
  228. receive_result(Ref, Timeout) ->
  229. receive
  230. {result, Ref, Result} ->
  231. {ok, Result};
  232. {Ref, Result} ->
  233. {ok, Result}
  234. after Timeout ->
  235. timeout
  236. end.
  237. connect_direct_tdengine(Config) ->
  238. Opts = [
  239. {host, to_bin(?config(td_host, Config))},
  240. {port, ?config(td_port, Config)},
  241. {username, to_bin(?TD_USERNAME)},
  242. {password, to_bin(?TD_PASSWORD)},
  243. {pool_size, 8}
  244. ],
  245. {ok, Con} = tdengine:start_link(Opts),
  246. Con.
  247. % These funs connect and then stop the tdengine connection
  248. connect_and_create_table(Config) ->
  249. ?WITH_CON(begin
  250. _ = directly_query(Con, ?SQL_DROP_TABLE),
  251. _ = directly_query(Con, ?SQL_DROP_STABLE),
  252. {ok, _} = directly_query(Con, ?SQL_CREATE_DATABASE, []),
  253. {ok, _} = directly_query(Con, ?SQL_CREATE_TABLE),
  254. {ok, _} = directly_query(Con, ?SQL_CREATE_STABLE)
  255. end).
  256. connect_and_clear_table(Config) ->
  257. ?WITH_CON({ok, _} = directly_query(Con, ?SQL_DELETE)).
  258. connect_and_get_payload(Config) ->
  259. ?WITH_CON(
  260. {ok, #{<<"code">> := 0, <<"data">> := Result}} = directly_query(Con, ?SQL_SELECT)
  261. ),
  262. Result.
  263. connect_and_exec(Config, SQL) ->
  264. ?WITH_CON({ok, _} = directly_query(Con, SQL)).
  265. connect_and_query(Config, SQL) ->
  266. ?WITH_CON(
  267. {ok, #{<<"code">> := 0, <<"data">> := Data}} = directly_query(Con, SQL)
  268. ),
  269. Data.
  270. directly_query(Con, Query) ->
  271. directly_query(Con, Query, [{db_name, ?TD_DATABASE}]).
  272. directly_query(Con, Query, QueryOpts) ->
  273. tdengine:insert(Con, Query, QueryOpts).
  274. is_success_check(Result) ->
  275. ?assertMatch({ok, #{<<"code">> := 0}}, Result).
  276. to_str(Atom) when is_atom(Atom) ->
  277. erlang:atom_to_list(Atom).
  278. %%------------------------------------------------------------------------------
  279. %% Testcases
  280. %%------------------------------------------------------------------------------
  281. t_create_via_http(Config) ->
  282. emqx_bridge_v2_testlib:t_create_via_http(Config).
  283. t_on_get_status(Config) ->
  284. emqx_bridge_v2_testlib:t_on_get_status(Config, #{failure_status => connecting}).
  285. t_start_stop(Config) ->
  286. emqx_bridge_v2_testlib:t_start_stop(Config, tdengine_connector_stop).
  287. t_invalid_data(Config) ->
  288. MakeMessageFun = fun() -> #{} end,
  289. IsSuccessCheck = fun(Result) ->
  290. ?assertMatch(
  291. {error, #{
  292. <<"code">> := 534,
  293. <<"desc">> := _
  294. }},
  295. Result
  296. )
  297. end,
  298. ok = emqx_bridge_v2_testlib:t_sync_query(
  299. Config, MakeMessageFun, IsSuccessCheck, tdengine_connector_query_return
  300. ),
  301. ok.
  302. t_simple_insert(Config) ->
  303. connect_and_clear_table(Config),
  304. MakeMessageFun = fun() ->
  305. #{payload => ?PAYLOAD, timestamp => 1668602148000, second_ts => 1668602148010}
  306. end,
  307. ok = emqx_bridge_v2_testlib:t_sync_query(
  308. Config, MakeMessageFun, fun is_success_check/1, tdengine_connector_query_return
  309. ),
  310. ?assertMatch(
  311. [[?PAYLOAD], [?PAYLOAD]],
  312. connect_and_get_payload(Config)
  313. ).
  314. t_batch_insert(Config) ->
  315. connect_and_clear_table(Config),
  316. ?assertMatch({ok, _}, emqx_bridge_v2_testlib:create_bridge(Config)),
  317. Size = 5,
  318. Ts = erlang:system_time(millisecond),
  319. {_, {ok, #{result := _Result}}} =
  320. ?wait_async_action(
  321. lists:foreach(
  322. fun(Idx) ->
  323. SentData = #{
  324. payload => ?PAYLOAD, timestamp => Ts + Idx, second_ts => Ts + Idx + 5000
  325. },
  326. send_message(Config, SentData)
  327. end,
  328. lists:seq(1, Size)
  329. ),
  330. #{?snk_kind := buffer_worker_flush_ack},
  331. 2_000
  332. ),
  333. DoubleSize = Size * 2,
  334. ?retry(
  335. _Sleep = 50,
  336. _Attempts = 30,
  337. ?assertMatch(
  338. [[DoubleSize]],
  339. connect_and_query(Config, "SELECT COUNT(1) FROM t_mqtt_msg")
  340. )
  341. ).
  342. t_auto_create_simple_insert(Config) ->
  343. ClientId = to_str(?FUNCTION_NAME),
  344. MakeMessageFun = fun() ->
  345. #{
  346. payload => ?PAYLOAD,
  347. timestamp => 1668602148000,
  348. second_ts => 1668602148000 + 100,
  349. clientid => ClientId
  350. }
  351. end,
  352. ok = emqx_bridge_v2_testlib:t_sync_query(
  353. Config, MakeMessageFun, fun is_success_check/1, tdengine_connector_query_return
  354. ),
  355. ?assertMatch(
  356. [[?PAYLOAD]],
  357. connect_and_query(Config, "SELECT payload FROM " ++ ClientId)
  358. ),
  359. ?assertMatch(
  360. [[?PAYLOAD]],
  361. connect_and_query(Config, "SELECT payload FROM test_" ++ ClientId)
  362. ),
  363. ?assertMatch(
  364. [[0]],
  365. connect_and_query(Config, "DROP TABLE " ++ ClientId)
  366. ),
  367. ?assertMatch(
  368. [[0]],
  369. connect_and_query(Config, "DROP TABLE test_" ++ ClientId)
  370. ).
  371. t_auto_create_batch_insert(Config) ->
  372. ClientId1 = "client1",
  373. ClientId2 = "client2",
  374. ?assertMatch({ok, _}, emqx_bridge_v2_testlib:create_bridge(Config)),
  375. Size1 = 2,
  376. Size2 = 3,
  377. Ts = erlang:system_time(millisecond),
  378. {_, {ok, #{result := _Result}}} =
  379. ?wait_async_action(
  380. lists:foreach(
  381. fun({Offset, ClientId, Size}) ->
  382. lists:foreach(
  383. fun(Idx) ->
  384. SentData = #{
  385. payload => ?PAYLOAD,
  386. timestamp => Ts + Idx + Offset,
  387. second_ts => Ts + Idx + Offset + 5000,
  388. clientid => ClientId
  389. },
  390. send_message(Config, SentData)
  391. end,
  392. lists:seq(1, Size)
  393. )
  394. end,
  395. [{0, ClientId1, Size1}, {100, ClientId2, Size2}]
  396. ),
  397. #{?snk_kind := buffer_worker_flush_ack},
  398. 2_000
  399. ),
  400. ?retry(
  401. _Sleep = 50,
  402. _Attempts = 30,
  403. lists:foreach(
  404. fun({Table, Size}) ->
  405. ?assertMatch(
  406. [[Size]],
  407. connect_and_query(Config, "SELECT COUNT(1) FROM " ++ Table)
  408. )
  409. end,
  410. lists:zip(
  411. [ClientId1, "test_" ++ ClientId1, ClientId2, "test_" ++ ClientId2],
  412. [Size1, Size1, Size2, Size2]
  413. )
  414. )
  415. ),
  416. lists:foreach(
  417. fun(E) ->
  418. ?assertMatch(
  419. [[0]],
  420. connect_and_query(Config, "DROP TABLE " ++ E)
  421. )
  422. end,
  423. [ClientId1, ClientId2, "test_" ++ ClientId1, "test_" ++ ClientId2]
  424. ).