metrics_SUITE.erl 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. %% Copyright (c) 2017, Loïc Hoguin <essen@ninenines.eu>
  2. %%
  3. %% Permission to use, copy, modify, and/or distribute this software for any
  4. %% purpose with or without fee is hereby granted, provided that the above
  5. %% copyright notice and this permission notice appear in all copies.
  6. %%
  7. %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. -module(metrics_SUITE).
  15. -compile(export_all).
  16. -compile(nowarn_export_all).
  17. -import(ct_helper, [config/2]).
  18. -import(ct_helper, [doc/1]).
  19. -import(cowboy_test, [gun_open/1]).
  20. -import(cowboy_test, [gun_down/1]).
  21. -import(cowboy_test, [raw_open/1]).
  22. -import(cowboy_test, [raw_send/2]).
  23. -import(cowboy_test, [raw_recv_head/1]).
  24. %% ct.
  25. all() ->
  26. cowboy_test:common_all().
  27. groups() ->
  28. cowboy_test:common_groups(ct_helper:all(?MODULE)).
  29. init_per_group(Name = http, Config) ->
  30. cowboy_test:init_http(Name, init_plain_opts(Config), Config);
  31. init_per_group(Name = https, Config) ->
  32. cowboy_test:init_http(Name, init_plain_opts(Config), Config);
  33. init_per_group(Name = h2, Config) ->
  34. cowboy_test:init_http2(Name, init_plain_opts(Config), Config);
  35. init_per_group(Name = h2c, Config) ->
  36. Config1 = cowboy_test:init_http(Name, init_plain_opts(Config), Config),
  37. lists:keyreplace(protocol, 1, Config1, {protocol, http2});
  38. init_per_group(Name = http_compress, Config) ->
  39. cowboy_test:init_http(Name, init_compress_opts(Config), Config);
  40. init_per_group(Name = https_compress, Config) ->
  41. cowboy_test:init_http(Name, init_compress_opts(Config), Config);
  42. init_per_group(Name = h2_compress, Config) ->
  43. cowboy_test:init_http2(Name, init_compress_opts(Config), Config);
  44. init_per_group(Name = h2c_compress, Config) ->
  45. Config1 = cowboy_test:init_http(Name, init_compress_opts(Config), Config),
  46. lists:keyreplace(protocol, 1, Config1, {protocol, http2}).
  47. end_per_group(Name, _) ->
  48. cowboy:stop_listener(Name).
  49. init_plain_opts(Config) ->
  50. #{
  51. env => #{dispatch => cowboy_router:compile(init_routes(Config))},
  52. metrics_callback => do_metrics_callback(),
  53. stream_handlers => [cowboy_metrics_h, cowboy_stream_h]
  54. }.
  55. init_compress_opts(Config) ->
  56. #{
  57. env => #{dispatch => cowboy_router:compile(init_routes(Config))},
  58. metrics_callback => do_metrics_callback(),
  59. stream_handlers => [cowboy_metrics_h, cowboy_compress_h, cowboy_stream_h]
  60. }.
  61. init_routes(_) -> [
  62. {"localhost", [
  63. {"/", hello_h, []},
  64. {"/default", default_h, []},
  65. {"/full/:key", echo_h, []},
  66. {"/resp/:key[/:arg]", resp_h, []},
  67. {"/ws_echo", ws_echo, []}
  68. ]}
  69. ].
  70. do_metrics_callback() ->
  71. fun(Metrics) ->
  72. Pid = case Metrics of
  73. #{req := #{headers := #{<<"x-test-pid">> := P}}} ->
  74. list_to_pid(binary_to_list(P));
  75. #{partial_req := #{headers := #{<<"x-test-pid">> := P}}} ->
  76. list_to_pid(binary_to_list(P));
  77. _ ->
  78. whereis(early_error_metrics)
  79. end,
  80. Pid ! {metrics, self(), Metrics},
  81. ok
  82. end.
  83. %% Tests.
  84. hello_world(Config) ->
  85. doc("Confirm metrics are correct for a normal GET request."),
  86. do_get("/", Config).
  87. do_get(Path, Config) ->
  88. %% Perform a GET request.
  89. ConnPid = gun_open(Config),
  90. Ref = gun:get(ConnPid, Path, [
  91. {<<"accept-encoding">>, <<"gzip">>},
  92. {<<"x-test-pid">>, pid_to_list(self())}
  93. ]),
  94. {response, nofin, 200, RespHeaders} = gun:await(ConnPid, Ref),
  95. {ok, RespBody} = gun:await_body(ConnPid, Ref),
  96. gun:close(ConnPid),
  97. %% Receive the metrics and validate them.
  98. receive
  99. {metrics, From, Metrics} ->
  100. %% Ensure the timestamps are in the expected order.
  101. #{
  102. req_start := ReqStart, req_end := ReqEnd,
  103. resp_start := RespStart, resp_end := RespEnd
  104. } = Metrics,
  105. true = (ReqStart =< RespStart)
  106. and (RespStart =< RespEnd)
  107. and (RespEnd =< ReqEnd),
  108. %% We didn't send a body.
  109. #{
  110. req_body_start := undefined,
  111. req_body_end := undefined,
  112. req_body_length := 0
  113. } = Metrics,
  114. %% We got a 200 response with a body.
  115. #{
  116. resp_status := 200,
  117. resp_headers := ExpectedRespHeaders,
  118. resp_body_length := RespBodyLen
  119. } = Metrics,
  120. %% The transfer-encoding header is hidden from stream handlers.
  121. ExpectedRespHeaders = maps:remove(<<"transfer-encoding">>,
  122. maps:from_list(RespHeaders)),
  123. true = byte_size(RespBody) > 0,
  124. true = RespBodyLen > 0,
  125. %% The request process executed normally.
  126. #{procs := Procs} = Metrics,
  127. [{_, #{
  128. spawn := ProcSpawn,
  129. exit := ProcExit,
  130. reason := normal
  131. }}] = maps:to_list(Procs),
  132. true = ProcSpawn =< ProcExit,
  133. %% Confirm other metadata are as expected.
  134. #{
  135. ref := _,
  136. pid := From,
  137. streamid := 1,
  138. reason := normal,
  139. req := #{},
  140. informational := []
  141. } = Metrics,
  142. %% All good!
  143. ok
  144. after 1000 ->
  145. error(timeout)
  146. end.
  147. post_body(Config) ->
  148. doc("Confirm metrics are correct for a normal POST request."),
  149. %% Perform a POST request.
  150. ConnPid = gun_open(Config),
  151. Body = <<0:8000000>>,
  152. Ref = gun:post(ConnPid, "/full/read_body", [
  153. {<<"accept-encoding">>, <<"gzip">>},
  154. {<<"x-test-pid">>, pid_to_list(self())}
  155. ], Body),
  156. {response, nofin, 200, RespHeaders} = gun:await(ConnPid, Ref),
  157. {ok, RespBody} = gun:await_body(ConnPid, Ref),
  158. gun:close(ConnPid),
  159. %% Receive the metrics and validate them.
  160. receive
  161. {metrics, From, Metrics} ->
  162. %% Ensure the timestamps are in the expected order.
  163. #{
  164. req_start := ReqStart, req_end := ReqEnd,
  165. resp_start := RespStart, resp_end := RespEnd
  166. } = Metrics,
  167. true = (ReqStart =< RespStart)
  168. and (RespStart =< RespEnd)
  169. and (RespEnd =< ReqEnd),
  170. %% We didn't send a body.
  171. #{
  172. req_body_start := ReqBodyStart,
  173. req_body_end := ReqBodyEnd,
  174. req_body_length := ReqBodyLen
  175. } = Metrics,
  176. true = ReqBodyStart =< ReqBodyEnd,
  177. ReqBodyLen = byte_size(Body),
  178. %% We got a 200 response with a body.
  179. #{
  180. resp_status := 200,
  181. resp_headers := ExpectedRespHeaders,
  182. resp_body_length := RespBodyLen
  183. } = Metrics,
  184. ExpectedRespHeaders = maps:from_list(RespHeaders),
  185. true = byte_size(RespBody) > 0,
  186. true = RespBodyLen > 0,
  187. %% The request process executed normally.
  188. #{procs := Procs} = Metrics,
  189. [{_, #{
  190. spawn := ProcSpawn,
  191. exit := ProcExit,
  192. reason := normal
  193. }}] = maps:to_list(Procs),
  194. true = ProcSpawn =< ProcExit,
  195. %% Confirm other metadata are as expected.
  196. #{
  197. ref := _,
  198. pid := From,
  199. streamid := 1,
  200. reason := normal,
  201. req := #{},
  202. informational := []
  203. } = Metrics,
  204. %% All good!
  205. ok
  206. after 1000 ->
  207. error(timeout)
  208. end.
  209. no_resp_body(Config) ->
  210. doc("Confirm metrics are correct for a default 204 response to a GET request."),
  211. %% Perform a GET request.
  212. ConnPid = gun_open(Config),
  213. Ref = gun:get(ConnPid, "/default", [
  214. {<<"accept-encoding">>, <<"gzip">>},
  215. {<<"x-test-pid">>, pid_to_list(self())}
  216. ]),
  217. {response, fin, 204, RespHeaders} = gun:await(ConnPid, Ref),
  218. gun:close(ConnPid),
  219. %% Receive the metrics and validate them.
  220. receive
  221. {metrics, From, Metrics} ->
  222. %% Ensure the timestamps are in the expected order.
  223. #{
  224. req_start := ReqStart, req_end := ReqEnd,
  225. resp_start := RespStart, resp_end := RespEnd
  226. } = Metrics,
  227. true = (ReqStart =< RespStart)
  228. and (RespStart =< RespEnd)
  229. and (RespEnd =< ReqEnd),
  230. %% We didn't send a body.
  231. #{
  232. req_body_start := undefined,
  233. req_body_end := undefined,
  234. req_body_length := 0
  235. } = Metrics,
  236. %% We got a 200 response with a body.
  237. #{
  238. resp_status := 204,
  239. resp_headers := ExpectedRespHeaders,
  240. resp_body_length := 0
  241. } = Metrics,
  242. ExpectedRespHeaders = maps:from_list(RespHeaders),
  243. %% The request process executed normally.
  244. #{procs := Procs} = Metrics,
  245. [{_, #{
  246. spawn := ProcSpawn,
  247. exit := ProcExit,
  248. reason := normal
  249. }}] = maps:to_list(Procs),
  250. true = ProcSpawn =< ProcExit,
  251. %% Confirm other metadata are as expected.
  252. #{
  253. ref := _,
  254. pid := From,
  255. streamid := 1,
  256. reason := normal,
  257. req := #{},
  258. informational := []
  259. } = Metrics,
  260. %% All good!
  261. ok
  262. after 1000 ->
  263. error(timeout)
  264. end.
  265. early_error(Config) ->
  266. case config(protocol, Config) of
  267. http -> do_early_error(Config);
  268. http2 -> doc("The callback early_error/5 is not currently used for HTTP/2.")
  269. end.
  270. do_early_error(Config) ->
  271. doc("Confirm metrics are correct for an early_error response."),
  272. %% Perform a malformed GET request.
  273. ConnPid = gun_open(Config),
  274. Ref = gun:get(ConnPid, "/", [
  275. {<<"accept-encoding">>, <<"gzip">>},
  276. {<<"host">>, <<"host:port">>},
  277. {<<"x-test-pid">>, pid_to_list(self())}
  278. ]),
  279. {response, fin, 400, RespHeaders} = gun:await(ConnPid, Ref),
  280. gun:close(ConnPid),
  281. %% Receive the metrics and validate them.
  282. receive
  283. {metrics, From, Metrics} ->
  284. %% Confirm the metadata is there as expected.
  285. #{
  286. ref := _,
  287. pid := From,
  288. streamid := 1,
  289. reason := {stream_error, 1, protocol_error, _},
  290. partial_req := #{},
  291. resp_status := 400,
  292. resp_headers := ExpectedRespHeaders,
  293. early_error_time := _,
  294. resp_body_length := 0
  295. } = Metrics,
  296. ExpectedRespHeaders = maps:from_list(RespHeaders),
  297. %% All good!
  298. ok
  299. after 1000 ->
  300. error(timeout)
  301. end.
  302. early_error_request_line(Config) ->
  303. case config(protocol, Config) of
  304. http -> do_early_error_request_line(Config);
  305. http2 -> doc("The callback early_error/5 is not currently used for HTTP/2.")
  306. end.
  307. do_early_error_request_line(Config) ->
  308. doc("Confirm metrics are correct for an early_error response "
  309. "that occurred on the request-line."),
  310. %% Register the process in order to receive the metrics event.
  311. register(early_error_metrics, self()),
  312. %% Send a malformed request-line.
  313. Client = raw_open(Config),
  314. ok = raw_send(Client, <<"FOO bar\r\n">>),
  315. {'HTTP/1.1', 400, _, Rest} = cow_http:parse_status_line(raw_recv_head(Client)),
  316. {RespHeaders, _} = cow_http:parse_headers(Rest),
  317. %% Receive the metrics and validate them.
  318. receive
  319. {metrics, From, Metrics} ->
  320. %% Confirm the metadata is there as expected.
  321. #{
  322. ref := _,
  323. pid := From,
  324. streamid := 1,
  325. reason := {connection_error, protocol_error, _},
  326. partial_req := #{},
  327. resp_status := 400,
  328. resp_headers := ExpectedRespHeaders,
  329. early_error_time := _,
  330. resp_body_length := 0
  331. } = Metrics,
  332. ExpectedRespHeaders = maps:from_list(RespHeaders),
  333. %% All good!
  334. ok
  335. after 1000 ->
  336. error(timeout)
  337. end.
  338. %% This test is identical to normal GET except for the handler.
  339. stream_reply(Config) ->
  340. doc("Confirm metrics are correct for long polling."),
  341. do_get("/resp/stream_reply2/200", Config).
  342. ws(Config) ->
  343. case config(protocol, Config) of
  344. http -> do_ws(Config);
  345. http2 -> doc("It is not currently possible to switch to Websocket over HTTP/2.")
  346. end.
  347. do_ws(Config) ->
  348. doc("Confirm metrics are correct when switching to Websocket."),
  349. ConnPid = gun_open(Config),
  350. {ok, http} = gun:await_up(ConnPid),
  351. gun:ws_upgrade(ConnPid, "/ws_echo", [
  352. {<<"accept-encoding">>, <<"gzip">>},
  353. {<<"x-test-pid">>, pid_to_list(self())}
  354. ]),
  355. receive
  356. {metrics, From, Metrics} ->
  357. %% Ensure the timestamps are in the expected order.
  358. #{
  359. req_start := ReqStart,
  360. req_end := ReqEnd
  361. } = Metrics,
  362. true = ReqStart =< ReqEnd,
  363. %% We didn't send a body.
  364. #{
  365. req_body_start := undefined,
  366. req_body_end := undefined,
  367. req_body_length := 0
  368. } = Metrics,
  369. %% We didn't send a response.
  370. #{
  371. resp_start := undefined,
  372. resp_end := undefined,
  373. resp_status := undefined,
  374. resp_headers := undefined,
  375. resp_body_length := 0
  376. } = Metrics,
  377. %% The request process may not have terminated before terminate
  378. %% is called. We therefore only check when it spawned.
  379. #{procs := Procs} = Metrics,
  380. [{_, #{
  381. spawn := _
  382. }}] = maps:to_list(Procs),
  383. %% Confirm other metadata are as expected.
  384. #{
  385. ref := _,
  386. pid := From,
  387. streamid := 1,
  388. reason := switch_protocol,
  389. req := #{},
  390. %% A 101 upgrade response was sent.
  391. informational := [#{
  392. status := 101,
  393. headers := #{
  394. <<"connection">> := <<"Upgrade">>,
  395. <<"upgrade">> := <<"websocket">>,
  396. <<"sec-websocket-accept">> := _
  397. },
  398. time := _
  399. }]
  400. } = Metrics,
  401. %% All good!
  402. ok
  403. after 1000 ->
  404. error(timeout)
  405. end,
  406. %% And of course the upgrade completed successfully after that.
  407. receive
  408. {gun_ws_upgrade, ConnPid, ok, _} ->
  409. ok
  410. after 1000 ->
  411. error(timeout)
  412. end,
  413. gun:close(ConnPid).