emqx_bridge_sqlserver_SUITE.erl 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. %%--------------------------------------------------------------------
  2. % Copyright (c) 2022-2024 EMQ Technologies Co., Ltd. All Rights Reserved.
  3. %%--------------------------------------------------------------------
  4. -module(emqx_bridge_sqlserver_SUITE).
  5. -compile(nowarn_export_all).
  6. -compile(export_all).
  7. -include("../include/emqx_bridge_sqlserver.hrl").
  8. -include_lib("eunit/include/eunit.hrl").
  9. -include_lib("common_test/include/ct.hrl").
  10. -include_lib("snabbkaffe/include/snabbkaffe.hrl").
  11. % SQL definitions
  12. -define(SQL_BRIDGE,
  13. "insert into t_mqtt_msg(msgid, topic, qos, payload) values ( ${id}, ${topic}, ${qos}, ${payload})"
  14. ).
  15. -define(SQL_SERVER_DRIVER, "ms-sql").
  16. -define(SQL_CREATE_DATABASE_IF_NOT_EXISTS,
  17. " IF NOT EXISTS(SELECT name FROM sys.databases WHERE name = 'mqtt')"
  18. " BEGIN"
  19. " CREATE DATABASE mqtt;"
  20. " END"
  21. ).
  22. -define(SQL_CREATE_TABLE_IN_DB_MQTT,
  23. " CREATE TABLE mqtt.dbo.t_mqtt_msg"
  24. " (id int PRIMARY KEY IDENTITY(1000000001,1) NOT NULL,"
  25. " msgid VARCHAR(64) NULL,"
  26. " topic VARCHAR(100) NULL,"
  27. " qos tinyint NOT NULL DEFAULT 0,"
  28. %% use VARCHAR to use utf8 encoding
  29. %% for default, sqlserver use utf16 encoding NVARCHAR()
  30. " payload VARCHAR(100) NULL,"
  31. " arrived DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)"
  32. ).
  33. -define(SQL_DROP_DB_MQTT, "DROP DATABASE mqtt").
  34. -define(SQL_DROP_TABLE, "DROP TABLE mqtt.dbo.t_mqtt_msg").
  35. -define(SQL_DELETE, "DELETE from mqtt.dbo.t_mqtt_msg").
  36. -define(SQL_SELECT, "SELECT payload FROM mqtt.dbo.t_mqtt_msg").
  37. -define(SQL_SELECT_COUNT, "SELECT COUNT(*) FROM mqtt.dbo.t_mqtt_msg").
  38. % DB defaults
  39. -define(SQL_SERVER_DATABASE, "mqtt").
  40. -define(SQL_SERVER_USERNAME, "sa").
  41. -define(SQL_SERVER_PASSWORD, "mqtt_public1").
  42. -define(BATCH_SIZE, 10).
  43. -define(REQUEST_TIMEOUT_MS, 500).
  44. -define(WORKER_POOL_SIZE, 4).
  45. -define(WITH_CON(Process),
  46. Con = connect_direct_sqlserver(Config),
  47. Process,
  48. ok = disconnect(Con)
  49. ).
  50. %% How to run it locally (all commands are run in $PROJ_ROOT dir):
  51. %% A: run ct on host
  52. %% 1. Start all deps services
  53. %% ```bash
  54. %% sudo docker compose -f .ci/docker-compose-file/docker-compose.yaml \
  55. %% -f .ci/docker-compose-file/docker-compose-sqlserver.yaml \
  56. %% -f .ci/docker-compose-file/docker-compose-toxiproxy.yaml \
  57. %% up --build
  58. %% ```
  59. %%
  60. %% 2. Run use cases with special environment variables
  61. %% 11433 is toxiproxy exported port.
  62. %% Local:
  63. %% ```bash
  64. %% SQLSERVER_HOST=toxiproxy SQLSERVER_PORT=11433 \
  65. %% PROXY_HOST=toxiproxy PROXY_PORT=1433 \
  66. %% ./rebar3 as test ct -c -v --readable true --name ct@127.0.0.1 \
  67. %% --suite apps/emqx_bridge_sqlserver/test/emqx_bridge_sqlserver_SUITE.erl
  68. %% ```
  69. %%
  70. %% B: run ct in docker container
  71. %% run script:
  72. %% ```bash
  73. %% ./scripts/ct/run.sh --ci --app apps/emqx_bridge_sqlserver/ -- \
  74. %% --name 'test@127.0.0.1' -c -v --readable true \
  75. %% --suite apps/emqx_bridge_sqlserver/test/emqx_bridge_sqlserver_SUITE.erl
  76. %% ````
  77. %%------------------------------------------------------------------------------
  78. %% CT boilerplate
  79. %%------------------------------------------------------------------------------
  80. all() ->
  81. [
  82. {group, async},
  83. {group, sync}
  84. ].
  85. groups() ->
  86. TCs = emqx_common_test_helpers:all(?MODULE),
  87. NonBatchCases = [t_write_timeout],
  88. BatchingGroups = [{group, with_batch}, {group, without_batch}],
  89. [
  90. {async, BatchingGroups},
  91. {sync, BatchingGroups},
  92. {with_batch, TCs -- NonBatchCases},
  93. {without_batch, TCs}
  94. ].
  95. init_per_group(async, Config) ->
  96. [{query_mode, async} | Config];
  97. init_per_group(sync, Config) ->
  98. [{query_mode, sync} | Config];
  99. init_per_group(with_batch, Config0) ->
  100. Config = [{enable_batch, true} | Config0],
  101. common_init(Config);
  102. init_per_group(without_batch, Config0) ->
  103. Config = [{enable_batch, false} | Config0],
  104. common_init(Config);
  105. init_per_group(_Group, Config) ->
  106. Config.
  107. end_per_group(Group, Config) when Group =:= with_batch; Group =:= without_batch ->
  108. connect_and_drop_table(Config),
  109. connect_and_drop_db(Config),
  110. Apps = ?config(apps, Config),
  111. ProxyHost = ?config(proxy_host, Config),
  112. ProxyPort = ?config(proxy_port, Config),
  113. emqx_common_test_helpers:reset_proxy(ProxyHost, ProxyPort),
  114. emqx_cth_suite:stop(Apps),
  115. ok;
  116. end_per_group(_Group, _Config) ->
  117. ok.
  118. init_per_suite(Config) ->
  119. Passfile = filename:join(?config(priv_dir, Config), "passfile"),
  120. ok = file:write_file(Passfile, <<?SQL_SERVER_PASSWORD>>),
  121. [{sqlserver_passfile, Passfile} | Config].
  122. end_per_suite(_Config) ->
  123. ok.
  124. init_per_testcase(_Testcase, Config) ->
  125. %% drop database and table
  126. %% connect_and_clear_table(Config),
  127. %% create a new one
  128. %% TODO: create a new database for each test case
  129. delete_bridge(Config),
  130. snabbkaffe:start_trace(),
  131. Config.
  132. end_per_testcase(_Testcase, Config) ->
  133. ProxyHost = ?config(proxy_host, Config),
  134. ProxyPort = ?config(proxy_port, Config),
  135. emqx_common_test_helpers:reset_proxy(ProxyHost, ProxyPort),
  136. connect_and_clear_table(Config),
  137. ok = snabbkaffe:stop(),
  138. delete_bridge(Config),
  139. ok.
  140. %%------------------------------------------------------------------------------
  141. %% Testcases
  142. %%------------------------------------------------------------------------------
  143. t_setup_via_config_and_publish(Config) ->
  144. ?assertMatch(
  145. {ok, _},
  146. create_bridge(Config)
  147. ),
  148. Val = str(erlang:unique_integer()),
  149. SentData = sent_data(Val),
  150. ?check_trace(
  151. begin
  152. ?wait_async_action(
  153. ?assertEqual(ok, send_message(Config, SentData)),
  154. #{?snk_kind := sqlserver_connector_query_return},
  155. 10_000
  156. ),
  157. ?assertMatch(
  158. [{Val}],
  159. connect_and_get_payload(Config)
  160. ),
  161. ok
  162. end,
  163. fun(Trace0) ->
  164. Trace = ?of_kind(sqlserver_connector_query_return, Trace0),
  165. ?assertMatch([#{result := ok}], Trace),
  166. ok
  167. end
  168. ),
  169. ok.
  170. t_undefined_vars_as_null(Config) ->
  171. ?assertMatch(
  172. {ok, _},
  173. create_bridge(Config, #{<<"undefined_vars_as_null">> => true})
  174. ),
  175. SentData = maps:put(payload, undefined, sent_data("tmp")),
  176. ?check_trace(
  177. begin
  178. ?wait_async_action(
  179. ?assertEqual(ok, send_message(Config, SentData)),
  180. #{?snk_kind := sqlserver_connector_query_return},
  181. 10_000
  182. ),
  183. ?assertMatch(
  184. [{null}],
  185. connect_and_get_payload(Config)
  186. ),
  187. ok
  188. end,
  189. fun(Trace0) ->
  190. Trace = ?of_kind(sqlserver_connector_query_return, Trace0),
  191. ?assertMatch([#{result := ok}], Trace),
  192. ok
  193. end
  194. ),
  195. ok.
  196. t_setup_via_http_api_and_publish(Config) ->
  197. BridgeType = ?config(sqlserver_bridge_type, Config),
  198. Name = ?config(sqlserver_name, Config),
  199. SQLServerConfig0 = ?config(sqlserver_config, Config),
  200. SQLServerConfig = SQLServerConfig0#{
  201. <<"name">> => Name,
  202. <<"type">> => BridgeType,
  203. %% NOTE: using literal password with HTTP API requests.
  204. <<"password">> => <<?SQL_SERVER_PASSWORD>>
  205. },
  206. ?assertMatch(
  207. {ok, _},
  208. create_bridge_http(SQLServerConfig)
  209. ),
  210. Val = str(erlang:unique_integer()),
  211. SentData = sent_data(Val),
  212. ?check_trace(
  213. begin
  214. ?wait_async_action(
  215. ?assertEqual(ok, send_message(Config, SentData)),
  216. #{?snk_kind := sqlserver_connector_query_return},
  217. 10_000
  218. ),
  219. ?assertMatch(
  220. [{Val}],
  221. connect_and_get_payload(Config)
  222. ),
  223. ok
  224. end,
  225. fun(Trace0) ->
  226. Trace = ?of_kind(sqlserver_connector_query_return, Trace0),
  227. ?assertMatch([#{result := ok}], Trace),
  228. ok
  229. end
  230. ),
  231. ok.
  232. t_get_status(Config) ->
  233. ?assertMatch(
  234. {ok, _},
  235. create_bridge(Config)
  236. ),
  237. ProxyPort = ?config(proxy_port, Config),
  238. ProxyHost = ?config(proxy_host, Config),
  239. ProxyName = ?config(proxy_name, Config),
  240. health_check_resource_ok(Config),
  241. emqx_common_test_helpers:with_failure(down, ProxyName, ProxyHost, ProxyPort, fun() ->
  242. health_check_resource_down(Config)
  243. end),
  244. ok.
  245. t_create_disconnected(Config) ->
  246. ProxyPort = ?config(proxy_port, Config),
  247. ProxyHost = ?config(proxy_host, Config),
  248. ProxyName = ?config(proxy_name, Config),
  249. emqx_common_test_helpers:with_failure(down, ProxyName, ProxyHost, ProxyPort, fun() ->
  250. ?assertMatch({ok, _}, create_bridge(Config)),
  251. health_check_resource_down(Config)
  252. end),
  253. timer:sleep(10_000),
  254. health_check_resource_ok(Config),
  255. ok.
  256. t_create_with_invalid_password(Config) ->
  257. BridgeType = ?config(sqlserver_bridge_type, Config),
  258. Name = ?config(sqlserver_name, Config),
  259. SQLServerConfig0 = ?config(sqlserver_config, Config),
  260. SQLServerConfig = SQLServerConfig0#{
  261. <<"name">> => Name,
  262. <<"type">> => BridgeType,
  263. <<"password">> => <<"wrong_password">>
  264. },
  265. ?check_trace(
  266. begin
  267. ?assertMatch(
  268. {ok, _},
  269. create_bridge_http(SQLServerConfig)
  270. )
  271. end,
  272. fun(Trace) ->
  273. ?assertMatch(
  274. [#{error := {start_pool_failed, _, _}}],
  275. ?of_kind(sqlserver_connector_start_failed, Trace)
  276. ),
  277. ok
  278. end
  279. ),
  280. ok.
  281. t_write_failure(Config) ->
  282. ProxyName = ?config(proxy_name, Config),
  283. ProxyPort = ?config(proxy_port, Config),
  284. ProxyHost = ?config(proxy_host, Config),
  285. QueryMode = ?config(query_mode, Config),
  286. Val = str(erlang:unique_integer()),
  287. SentData = sent_data(Val),
  288. {{ok, _}, {ok, _}} =
  289. ?wait_async_action(
  290. create_bridge(Config),
  291. #{?snk_kind := resource_connected_enter},
  292. 20_000
  293. ),
  294. emqx_common_test_helpers:with_failure(down, ProxyName, ProxyHost, ProxyPort, fun() ->
  295. case QueryMode of
  296. sync ->
  297. ?assertMatch(
  298. {error, {resource_error, #{reason := timeout}}},
  299. send_message(Config, SentData)
  300. );
  301. async ->
  302. ?assertMatch(
  303. ok, send_message(Config, SentData)
  304. )
  305. end
  306. end),
  307. ok.
  308. t_write_timeout(_Config) ->
  309. %% msodbc driver handled all connection exceptions
  310. %% the case is same as t_write_failure/1
  311. ok.
  312. t_simple_query(Config) ->
  313. BatchSize = batch_size(Config),
  314. ?assertMatch(
  315. {ok, _},
  316. create_bridge(Config)
  317. ),
  318. {Requests, Vals} = gen_batch_req(Config, BatchSize),
  319. ?check_trace(
  320. begin
  321. ?wait_async_action(
  322. begin
  323. [?assertEqual(ok, query_resource(Config, Request)) || Request <- Requests]
  324. end,
  325. #{?snk_kind := sqlserver_connector_query_return},
  326. 10_000
  327. ),
  328. %% just assert the data count is correct
  329. ?assertMatch(
  330. BatchSize,
  331. connect_and_get_count(Config)
  332. ),
  333. %% assert the data order is correct
  334. ?assertMatch(
  335. Vals,
  336. connect_and_get_payload(Config)
  337. )
  338. end,
  339. fun(Trace0) ->
  340. Trace = ?of_kind(sqlserver_connector_query_return, Trace0),
  341. case BatchSize of
  342. 1 ->
  343. ?assertMatch([#{result := ok}], Trace);
  344. _ ->
  345. [?assertMatch(#{result := ok}, Trace1) || Trace1 <- Trace]
  346. end,
  347. ok
  348. end
  349. ),
  350. ok.
  351. -define(MISSING_TINYINT_ERROR,
  352. "[Microsoft][ODBC Driver 18 for SQL Server][SQL Server]"
  353. "Conversion failed when converting the varchar value 'undefined' to data type tinyint. SQLSTATE IS: 22018"
  354. ).
  355. t_missing_data(Config) ->
  356. QueryMode = ?config(query_mode, Config),
  357. ?assertMatch(
  358. {ok, _},
  359. create_bridge(Config)
  360. ),
  361. Result = send_message(Config, #{}),
  362. case QueryMode of
  363. sync ->
  364. ?assertMatch(
  365. {error, {unrecoverable_error, {invalid_request, ?MISSING_TINYINT_ERROR}}},
  366. Result
  367. );
  368. async ->
  369. ?assertMatch(
  370. ok, send_message(Config, #{})
  371. )
  372. end,
  373. ok.
  374. t_bad_parameter(Config) ->
  375. QueryMode = ?config(query_mode, Config),
  376. ?assertMatch(
  377. {ok, _},
  378. create_bridge(Config)
  379. ),
  380. Result = send_message(Config, #{}),
  381. case QueryMode of
  382. sync ->
  383. ?assertMatch(
  384. {error, {unrecoverable_error, {invalid_request, ?MISSING_TINYINT_ERROR}}},
  385. Result
  386. );
  387. async ->
  388. ?assertMatch(
  389. ok, send_message(Config, #{})
  390. )
  391. end,
  392. ok.
  393. %%------------------------------------------------------------------------------
  394. %% Helper fns
  395. %%------------------------------------------------------------------------------
  396. common_init(ConfigT) ->
  397. Host = os:getenv("SQLSERVER_HOST", "toxiproxy"),
  398. Port = list_to_integer(os:getenv("SQLSERVER_PORT", str(?SQLSERVER_DEFAULT_PORT))),
  399. Config0 = [
  400. {sqlserver_host, Host},
  401. {sqlserver_port, Port},
  402. %% see also for `proxy_name` : $PROJ_ROOT/.ci/docker-compose-file/toxiproxy.json
  403. {proxy_name, "sqlserver"},
  404. {batch_size, batch_size(ConfigT)}
  405. | ConfigT
  406. ],
  407. BridgeType = proplists:get_value(bridge_type, Config0, <<"sqlserver">>),
  408. case emqx_common_test_helpers:is_tcp_server_available(Host, Port) of
  409. true ->
  410. % Setup toxiproxy
  411. ProxyHost = os:getenv("PROXY_HOST", "toxiproxy"),
  412. ProxyPort = list_to_integer(os:getenv("PROXY_PORT", "8474")),
  413. emqx_common_test_helpers:reset_proxy(ProxyHost, ProxyPort),
  414. Apps = emqx_cth_suite:start(
  415. [
  416. emqx_conf,
  417. emqx_bridge_sqlserver,
  418. emqx_bridge,
  419. emqx_management,
  420. emqx_mgmt_api_test_util:emqx_dashboard()
  421. ],
  422. #{work_dir => emqx_cth_suite:work_dir(Config0)}
  423. ),
  424. % Connect to sqlserver directly
  425. % drop old db and table, and then create new ones
  426. connect_and_create_db_and_table(Config0),
  427. {Name, SQLServerConf} = sqlserver_config(BridgeType, Config0),
  428. Config =
  429. [
  430. {apps, Apps},
  431. {sqlserver_config, SQLServerConf},
  432. {sqlserver_bridge_type, BridgeType},
  433. {sqlserver_name, Name},
  434. {proxy_host, ProxyHost},
  435. {proxy_port, ProxyPort}
  436. | Config0
  437. ],
  438. Config;
  439. false ->
  440. case os:getenv("IS_CI") of
  441. "yes" ->
  442. throw(no_sqlserver);
  443. _ ->
  444. {skip, no_sqlserver}
  445. end
  446. end.
  447. sqlserver_config(BridgeType, Config) ->
  448. Port = integer_to_list(?config(sqlserver_port, Config)),
  449. Server = ?config(sqlserver_host, Config) ++ ":" ++ Port,
  450. Name = atom_to_binary(?MODULE),
  451. BatchSize = batch_size(Config),
  452. QueryMode = ?config(query_mode, Config),
  453. Passfile = ?config(sqlserver_passfile, Config),
  454. ConfigString =
  455. io_lib:format(
  456. "bridges.~s.~s {\n"
  457. " enable = true\n"
  458. " server = ~p\n"
  459. " database = ~p\n"
  460. " username = ~p\n"
  461. " password = ~p\n"
  462. " sql = ~p\n"
  463. " driver = ~p\n"
  464. " resource_opts = {\n"
  465. " request_ttl = 500ms\n"
  466. " batch_size = ~b\n"
  467. " query_mode = ~s\n"
  468. " worker_pool_size = ~b\n"
  469. " }\n"
  470. "}",
  471. [
  472. BridgeType,
  473. Name,
  474. Server,
  475. ?SQL_SERVER_DATABASE,
  476. ?SQL_SERVER_USERNAME,
  477. "file://" ++ Passfile,
  478. ?SQL_BRIDGE,
  479. ?SQL_SERVER_DRIVER,
  480. BatchSize,
  481. QueryMode,
  482. ?WORKER_POOL_SIZE
  483. ]
  484. ),
  485. {Name, parse_and_check(ConfigString, BridgeType, Name)}.
  486. parse_and_check(ConfigString, BridgeType, Name) ->
  487. {ok, RawConf} = hocon:binary(ConfigString, #{format => map}),
  488. hocon_tconf:check_plain(emqx_bridge_schema, RawConf, #{required => false, atom_key => false}),
  489. #{<<"bridges">> := #{BridgeType := #{Name := Config}}} = RawConf,
  490. Config.
  491. create_bridge(Config) ->
  492. create_bridge(Config, _Overrides = #{}).
  493. create_bridge(Config, Overrides) ->
  494. BridgeType = ?config(sqlserver_bridge_type, Config),
  495. Name = ?config(sqlserver_name, Config),
  496. SSConfig0 = ?config(sqlserver_config, Config),
  497. SSConfig = emqx_utils_maps:deep_merge(SSConfig0, Overrides),
  498. emqx_bridge:create(BridgeType, Name, SSConfig).
  499. delete_bridge(Config) ->
  500. BridgeType = ?config(sqlserver_bridge_type, Config),
  501. Name = ?config(sqlserver_name, Config),
  502. emqx_bridge:remove(BridgeType, Name).
  503. create_bridge_http(Params) ->
  504. Path = emqx_mgmt_api_test_util:api_path(["bridges"]),
  505. AuthHeader = emqx_mgmt_api_test_util:auth_header_(),
  506. case emqx_mgmt_api_test_util:request_api(post, Path, "", AuthHeader, Params) of
  507. {ok, Res} -> {ok, emqx_utils_json:decode(Res, [return_maps])};
  508. Error -> Error
  509. end.
  510. send_message(Config, Payload) ->
  511. Name = ?config(sqlserver_name, Config),
  512. BridgeType = ?config(sqlserver_bridge_type, Config),
  513. ActionId = emqx_bridge_v2:id(BridgeType, Name),
  514. emqx_bridge_v2:query(BridgeType, Name, {ActionId, Payload}, #{}).
  515. query_resource(Config, Request) ->
  516. Name = ?config(sqlserver_name, Config),
  517. BridgeType = ?config(sqlserver_bridge_type, Config),
  518. ID = emqx_bridge_v2:id(BridgeType, Name),
  519. ResID = emqx_connector_resource:resource_id(BridgeType, Name),
  520. emqx_resource:query(ID, Request, #{timeout => 1_000, connector_resource_id => ResID}).
  521. query_resource_async(Config, Request) ->
  522. Name = ?config(sqlserver_name, Config),
  523. BridgeType = ?config(sqlserver_bridge_type, Config),
  524. Ref = alias([reply]),
  525. AsyncReplyFun = fun(Result) -> Ref ! {result, Ref, Result} end,
  526. ResourceID = emqx_bridge_resource:resource_id(BridgeType, Name),
  527. Return = emqx_resource:query(ResourceID, Request, #{
  528. timeout => 500, async_reply_fun => {AsyncReplyFun, []}
  529. }),
  530. {Return, Ref}.
  531. resource_id(Config) ->
  532. Name = ?config(sqlserver_name, Config),
  533. BridgeType = ?config(sqlserver_bridge_type, Config),
  534. _ResourceID = emqx_bridge_resource:resource_id(BridgeType, Name).
  535. health_check_resource_ok(Config) ->
  536. BridgeType = ?config(sqlserver_bridge_type, Config),
  537. Name = ?config(sqlserver_name, Config),
  538. % Wait for reconnection.
  539. ?retry(
  540. _Sleep = 1_000,
  541. _Attempts = 10,
  542. begin
  543. ?assertEqual({ok, connected}, emqx_resource_manager:health_check(resource_id(Config))),
  544. ?assertMatch(#{status := connected}, emqx_bridge_v2:health_check(BridgeType, Name))
  545. end
  546. ).
  547. health_check_resource_down(Config) ->
  548. case emqx_resource_manager:health_check(resource_id(Config)) of
  549. {ok, Status} when Status =:= disconnected orelse Status =:= connecting ->
  550. ok;
  551. {error, timeout} ->
  552. ok;
  553. Other ->
  554. ?assert(
  555. false, lists:flatten(io_lib:format("invalid health check result:~p~n", [Other]))
  556. )
  557. end.
  558. receive_result(Ref, Timeout) ->
  559. receive
  560. {result, Ref, Result} ->
  561. {ok, Result};
  562. {Ref, Result} ->
  563. {ok, Result}
  564. after Timeout ->
  565. timeout
  566. end.
  567. connect_direct_sqlserver(Config) ->
  568. Opts = [
  569. {host, ?config(sqlserver_host, Config)},
  570. {port, ?config(sqlserver_port, Config)},
  571. {username, ?SQL_SERVER_USERNAME},
  572. {password, ?SQL_SERVER_PASSWORD},
  573. {driver, ?SQL_SERVER_DRIVER},
  574. {pool_size, 8}
  575. ],
  576. {ok, Con} = connect(Opts),
  577. Con.
  578. connect(Options) ->
  579. ConnectStr = lists:concat(conn_str(Options, [])),
  580. Opts = proplists:get_value(options, Options, []),
  581. odbc:connect(ConnectStr, Opts).
  582. disconnect(Ref) ->
  583. odbc:disconnect(Ref).
  584. % These funs connect and then stop the sqlserver connection
  585. connect_and_create_db_and_table(Config) ->
  586. ?WITH_CON(begin
  587. {updated, undefined} = directly_query(Con, ?SQL_CREATE_DATABASE_IF_NOT_EXISTS),
  588. {updated, undefined} = directly_query(Con, ?SQL_CREATE_TABLE_IN_DB_MQTT)
  589. end).
  590. connect_and_drop_db(Config) ->
  591. ?WITH_CON({updated, undefined} = directly_query(Con, ?SQL_DROP_DB_MQTT)).
  592. connect_and_drop_table(Config) ->
  593. ?WITH_CON({updated, undefined} = directly_query(Con, ?SQL_DROP_TABLE)).
  594. connect_and_clear_table(Config) ->
  595. ?WITH_CON({updated, _} = directly_query(Con, ?SQL_DELETE)).
  596. connect_and_get_payload(Config) ->
  597. ?WITH_CON(
  598. {selected, ["payload"], Rows} = directly_query(Con, ?SQL_SELECT)
  599. ),
  600. Rows.
  601. connect_and_get_count(Config) ->
  602. ?WITH_CON(
  603. {selected, [[]], [{Count}]} = directly_query(Con, ?SQL_SELECT_COUNT)
  604. ),
  605. Count.
  606. directly_query(Con, Query) ->
  607. directly_query(Con, Query, ?REQUEST_TIMEOUT_MS).
  608. directly_query(Con, Query, Timeout) ->
  609. odbc:sql_query(Con, Query, Timeout).
  610. %%--------------------------------------------------------------------
  611. %% help functions
  612. %%--------------------------------------------------------------------
  613. batch_size(Config) ->
  614. case ?config(enable_batch, Config) of
  615. true -> ?BATCH_SIZE;
  616. false -> 1
  617. end.
  618. conn_str([], Acc) ->
  619. lists:join(";", ["Encrypt=YES", "TrustServerCertificate=YES" | Acc]);
  620. conn_str([{driver, Driver} | Opts], Acc) ->
  621. conn_str(Opts, ["Driver=" ++ str(Driver) | Acc]);
  622. conn_str([{host, Host} | Opts], Acc) ->
  623. Port = proplists:get_value(port, Opts, str(?SQLSERVER_DEFAULT_PORT)),
  624. NOpts = proplists:delete(port, Opts),
  625. conn_str(NOpts, ["Server=" ++ str(Host) ++ "," ++ str(Port) | Acc]);
  626. conn_str([{port, Port} | Opts], Acc) ->
  627. Host = proplists:get_value(host, Opts, "localhost"),
  628. NOpts = proplists:delete(host, Opts),
  629. conn_str(NOpts, ["Server=" ++ str(Host) ++ "," ++ str(Port) | Acc]);
  630. conn_str([{database, Database} | Opts], Acc) ->
  631. conn_str(Opts, ["Database=" ++ str(Database) | Acc]);
  632. conn_str([{username, Username} | Opts], Acc) ->
  633. conn_str(Opts, ["UID=" ++ str(Username) | Acc]);
  634. conn_str([{password, Password} | Opts], Acc) ->
  635. conn_str(Opts, ["PWD=" ++ str(Password) | Acc]);
  636. conn_str([{_, _} | Opts], Acc) ->
  637. conn_str(Opts, Acc).
  638. sent_data(Payload) ->
  639. #{
  640. payload => to_bin(Payload),
  641. id => <<"0005F8F84FFFAFB9F44200000D810002">>,
  642. topic => <<"test/topic">>,
  643. qos => 0
  644. }.
  645. gen_batch_req(Config, Count) when
  646. is_integer(Count) andalso Count > 0
  647. ->
  648. BridgeType = ?config(sqlserver_bridge_type, Config),
  649. Name = ?config(sqlserver_name, Config),
  650. ActionId = emqx_bridge_v2:id(BridgeType, Name),
  651. Vals = [{str(erlang:unique_integer())} || _Seq <- lists:seq(1, Count)],
  652. Requests = [{ActionId, sent_data(Payload)} || {Payload} <- Vals],
  653. {Requests, Vals};
  654. gen_batch_req(_Config, Count) ->
  655. ct:pal("Gen batch requests failed with unexpected Count: ~p", [Count]).
  656. str(List) when is_list(List) ->
  657. unicode:characters_to_list(List, utf8);
  658. str(Bin) when is_binary(Bin) ->
  659. unicode:characters_to_list(Bin, utf8);
  660. str(Num) when is_number(Num) ->
  661. number_to_list(Num).
  662. number_to_list(Int) when is_integer(Int) ->
  663. integer_to_list(Int);
  664. number_to_list(Float) when is_float(Float) ->
  665. float_to_list(Float, [{decimals, 10}, compact]).
  666. to_bin(List) when is_list(List) ->
  667. unicode:characters_to_binary(List, utf8);
  668. to_bin(Bin) when is_binary(Bin) ->
  669. Bin.