cowboy_tracer_h.erl 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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(cowboy_tracer_h).
  15. -behavior(cowboy_stream).
  16. -export([init/3]).
  17. -export([data/4]).
  18. -export([info/3]).
  19. -export([terminate/3]).
  20. -export([early_error/5]).
  21. -export([set_trace_patterns/0]).
  22. -export([tracer_process/3]).
  23. -export([system_continue/3]).
  24. -export([system_terminate/4]).
  25. -export([system_code_change/4]).
  26. -type match_predicate()
  27. :: fun((cowboy_stream:streamid(), cowboy_req:req(), cowboy:opts()) -> boolean()).
  28. -type tracer_match_specs() :: [match_predicate()
  29. | {method, binary()}
  30. | {host, binary()}
  31. | {path, binary()}
  32. | {path_start, binary()}
  33. | {header, binary()}
  34. | {header, binary(), binary()}
  35. | {peer_ip, inet:ip_address()}
  36. ].
  37. -export_type([tracer_match_specs/0]).
  38. -type tracer_callback() :: fun((init | terminate | tuple(), any()) -> any()).
  39. -export_type([tracer_callback/0]).
  40. -spec init(cowboy_stream:streamid(), cowboy_req:req(), cowboy:opts())
  41. -> {cowboy_stream:commands(), any()}.
  42. init(StreamID, Req, Opts) ->
  43. init_tracer(StreamID, Req, Opts),
  44. cowboy_stream:init(StreamID, Req, Opts).
  45. -spec data(cowboy_stream:streamid(), cowboy_stream:fin(), cowboy_req:resp_body(), State)
  46. -> {cowboy_stream:commands(), State} when State::any().
  47. data(StreamID, IsFin, Data, Next) ->
  48. cowboy_stream:data(StreamID, IsFin, Data, Next).
  49. -spec info(cowboy_stream:streamid(), any(), State)
  50. -> {cowboy_stream:commands(), State} when State::any().
  51. info(StreamID, Info, Next) ->
  52. cowboy_stream:info(StreamID, Info, Next).
  53. -spec terminate(cowboy_stream:streamid(), cowboy_stream:reason(), any()) -> any().
  54. terminate(StreamID, Reason, Next) ->
  55. cowboy_stream:terminate(StreamID, Reason, Next).
  56. -spec early_error(cowboy_stream:streamid(), cowboy_stream:reason(),
  57. cowboy_stream:partial_req(), Resp, cowboy:opts()) -> Resp
  58. when Resp::cowboy_stream:resp_command().
  59. early_error(StreamID, Reason, PartialReq, Resp, Opts) ->
  60. cowboy_stream:early_error(StreamID, Reason, PartialReq, Resp, Opts).
  61. %% API.
  62. %% These trace patterns are most likely not suitable for production.
  63. -spec set_trace_patterns() -> ok.
  64. set_trace_patterns() ->
  65. erlang:trace_pattern({'_', '_', '_'}, [{'_', [], [{return_trace}]}], [local]),
  66. erlang:trace_pattern(on_load, [{'_', [], [{return_trace}]}], [local]),
  67. ok.
  68. %% Internal.
  69. init_tracer(StreamID, Req, Opts=#{tracer_match_specs := List, tracer_callback := _}) ->
  70. case match(List, StreamID, Req, Opts) of
  71. false ->
  72. ok;
  73. true ->
  74. start_tracer(StreamID, Req, Opts)
  75. end;
  76. %% When the options tracer_match_specs or tracer_callback
  77. %% are not provided we do not enable tracing.
  78. init_tracer(_, _, _) ->
  79. ok.
  80. match([], _, _, _) ->
  81. true;
  82. match([Predicate|Tail], StreamID, Req, Opts) when is_function(Predicate) ->
  83. case Predicate(StreamID, Req, Opts) of
  84. true -> match(Tail, StreamID, Req, Opts);
  85. false -> false
  86. end;
  87. match([{method, Value}|Tail], StreamID, Req=#{method := Value}, Opts) ->
  88. match(Tail, StreamID, Req, Opts);
  89. match([{host, Value}|Tail], StreamID, Req=#{host := Value}, Opts) ->
  90. match(Tail, StreamID, Req, Opts);
  91. match([{path, Value}|Tail], StreamID, Req=#{path := Value}, Opts) ->
  92. match(Tail, StreamID, Req, Opts);
  93. match([{path_start, PathStart}|Tail], StreamID, Req=#{path := Path}, Opts) ->
  94. Len = byte_size(PathStart),
  95. case Path of
  96. <<PathStart:Len/binary, _/bits>> -> match(Tail, StreamID, Req, Opts);
  97. _ -> false
  98. end;
  99. match([{header, Name}|Tail], StreamID, Req=#{headers := Headers}, Opts) ->
  100. case Headers of
  101. #{Name := _} -> match(Tail, StreamID, Req, Opts);
  102. _ -> false
  103. end;
  104. match([{header, Name, Value}|Tail], StreamID, Req=#{headers := Headers}, Opts) ->
  105. case Headers of
  106. #{Name := Value} -> match(Tail, StreamID, Req, Opts);
  107. _ -> false
  108. end;
  109. match([{peer_ip, IP}|Tail], StreamID, Req=#{peer := {IP, _}}, Opts) ->
  110. match(Tail, StreamID, Req, Opts);
  111. match(_, _, _, _) ->
  112. false.
  113. %% We only start the tracer if one wasn't started before.
  114. start_tracer(StreamID, Req, Opts) ->
  115. case erlang:trace_info(self(), tracer) of
  116. {tracer, []} ->
  117. TracerPid = proc_lib:spawn_link(?MODULE, tracer_process, [StreamID, Req, Opts]),
  118. %% The default flags are probably not suitable for production.
  119. Flags = maps:get(tracer_flags, Opts, [
  120. send, 'receive', call, return_to,
  121. procs, ports, monotonic_timestamp,
  122. %% The set_on_spawn flag is necessary to catch events
  123. %% from request processes.
  124. set_on_spawn
  125. ]),
  126. erlang:trace(self(), true, [{tracer, TracerPid}|Flags]),
  127. ok;
  128. _ ->
  129. ok
  130. end.
  131. %% Tracer process.
  132. -spec tracer_process(_, _, _) -> no_return().
  133. tracer_process(StreamID, Req=#{pid := Parent}, Opts=#{tracer_callback := Fun}) ->
  134. %% This is necessary because otherwise the tracer could stop
  135. %% before it has finished processing the events in its queue.
  136. process_flag(trap_exit, true),
  137. State = Fun(init, {StreamID, Req, Opts}),
  138. tracer_loop(Parent, Opts, State).
  139. tracer_loop(Parent, Opts=#{tracer_callback := Fun}, State0) ->
  140. receive
  141. Msg when element(1, Msg) =:= trace_ts ->
  142. State = Fun(Msg, State0),
  143. tracer_loop(Parent, Opts, State);
  144. {'EXIT', Parent, Reason} ->
  145. tracer_terminate(Reason, Opts, State0);
  146. {system, From, Request} ->
  147. sys:handle_system_msg(Request, From, Parent, ?MODULE, [], {Opts, State0});
  148. Msg ->
  149. cowboy:log(warning, "~p: Tracer process received stray message ~9999p~n",
  150. [?MODULE, Msg], Opts),
  151. tracer_loop(Parent, Opts, State0)
  152. end.
  153. -spec tracer_terminate(_, _, _) -> no_return().
  154. tracer_terminate(Reason, #{tracer_callback := Fun}, State) ->
  155. _ = Fun(terminate, State),
  156. exit(Reason).
  157. %% System callbacks.
  158. -spec system_continue(pid(), _, {cowboy:opts(), any()}) -> no_return().
  159. system_continue(Parent, _, {Opts, State}) ->
  160. tracer_loop(Parent, Opts, State).
  161. -spec system_terminate(any(), _, _, _) -> no_return().
  162. system_terminate(Reason, _, _, {Opts, State}) ->
  163. tracer_terminate(Reason, Opts, State).
  164. -spec system_code_change(Misc, _, _, _) -> {ok, Misc} when Misc::any().
  165. system_code_change(Misc, _, _, _) ->
  166. {ok, Misc}.