1 -module(beam_stats_consumer_graphite).
3 -include("include/beam_stats.hrl").
4 -include("beam_stats_logging.hrl").
6 -behaviour(beam_stats_consumer).
19 {consumption_interval , non_neg_integer()}
20 | {host , inet:ip_address() | inet:hostname()}
21 | {port , inet:port_number()}
22 | {timeout , timeout()}
26 { sock = none :: hope_option:t(Socket :: port())
27 , host :: inet:ip_address() | inet:hostname()
28 , port :: inet:port_number()
29 , timeout :: timeout()
35 -define(DEFAULT_HOST , "localhost").
36 -define(DEFAULT_PORT , 2003).
37 -define(DEFAULT_TIMEOUT , 5000).
39 -spec init([option()]) ->
40 {non_neg_integer(), state()}.
42 Get = fun (Key, Default) -> hope_kv_list:get(Options, Key, Default) end,
43 ConsumptionInterval = Get(consumption_interval, 60000),
46 , host = Get(host , ?DEFAULT_HOST)
47 , port = Get(port , ?DEFAULT_PORT)
48 , timeout = Get(timeout , ?DEFAULT_TIMEOUT)
50 {ConsumptionInterval, State}.
52 -spec consume(beam_stats_consumer:queue(), state()) ->
54 consume(Q, #state{}=State1) ->
55 Payload = beam_stats_queue_to_binary(Q),
56 State2 = try_to_connect_if_no_socket(State1),
57 try_to_send(State2, Payload).
59 -spec terminate(state()) ->
61 terminate(#state{sock=SockOpt}) ->
62 ok = hope_option:iter(SockOpt, fun gen_tcp:close/1),
65 %% ============================================================================
67 -spec try_to_send(state(), binary()) ->
69 try_to_send(#state{sock=none}=State, _) ->
70 ?log_error("Sending failed. No socket in state."),
71 % TODO: Maybe schedule retry?
73 try_to_send(#state{sock={some, Sock}}=State, Payload) ->
74 case gen_tcp:send(Sock, Payload)
78 ?log_error("gen_tcp:send(~p, ~p) -> ~p", [Sock, Payload, Error]),
79 % TODO: Maybe schedule retry?
80 ok = gen_tcp:close(Sock),
81 State#state{sock=none}
84 -spec try_to_connect_if_no_socket(state()) ->
86 try_to_connect_if_no_socket(#state{sock={some, _}}=State) ->
88 try_to_connect_if_no_socket(
96 Options = [binary, {active, false}],
97 case gen_tcp:connect(Host, Port, Options, Timeout)
99 State#state{sock = {some, Sock}}
100 ; {error, _}=Error ->
102 "gen_tcp:connect(~p, ~p, ~p, ~p) -> ~p",
103 [Host, Port, Options, Timeout, Error]
105 State#state{sock = none}
108 -spec beam_stats_queue_to_binary(beam_stats_consumer:queue()) ->
110 beam_stats_queue_to_binary(Q) ->
111 Bins = [beam_stats_to_bins(B) || B <- queue:to_list(Q)],
112 iolist_to_binary(Bins).
114 -spec beam_stats_to_bins(beam_stats:t()) ->
116 beam_stats_to_bins(#beam_stats{}=BeamStats) ->
117 Msgs = beam_stats_msg_graphite:of_beam_stats(BeamStats),
118 lists:map(fun beam_stats_msg_graphite:to_bin/1, Msgs).