Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 62 additions & 8 deletions src/imetrics.erl
Original file line number Diff line number Diff line change
Expand Up @@ -105,16 +105,18 @@ add(Name, Value) ->
add(Name, #{}, Value).

%% Counters are sharded by scheduler: each series is stored as up to
%% erlang:system_info(schedulers) rows keyed {TagsWithName, SchedulerId}, so
%% erlang:system_info(schedulers) rows keyed {{Name, Tags}, SchedulerId}, so
%% concurrent adds to the same series don't serialize on one ETS row lock.
%% Readers sum the shards (see get_counter_points/0). The return value is the
%% calling scheduler's shard after the increment, not the series total.
%%
%% Name and Tags are stored in the ets table and converted to binaries on the
%% scrape path. Invalid metrics will be silently dropped on scrape.
add(Name, Tags, Value) ->
?CATCH_KNOWN_EXC(
begin
true = is_integer(Value),
TagsWithName = imetrics_utils:bin(Tags#{ name => Name }),
Key = {TagsWithName, erlang:system_info(scheduler_id)},
Key = {{Name, Tags}, erlang:system_info(scheduler_id)},
ets:update_counter(imetrics_counters, Key, Value, {Key, 0})
end
).
Expand Down Expand Up @@ -421,9 +423,18 @@ get_hist() ->
delete_counter(Name, Tags) ->
?CATCH_KNOWN_EXC(
begin
% Find all keys that match the binary representation of the metric name. This
% ensures that no metric is left to be scraped by this name.
TagsWithName = imetrics_utils:bin(Tags#{ name => Name }),
lists:foreach(fun(Shard) -> ets:delete(imetrics_counters, {TagsWithName, Shard}) end,
lists:seq(1, erlang:system_info(schedulers))),
Keys = ets:foldl(fun({{{N, T}, _Shard} = Key, _}, Acc) ->
try imetrics_utils:bin(T#{ name => N }) of
TagsWithName -> [Key | Acc];
_ -> Acc
catch
error:_ -> Acc
end
end, [], imetrics_counters),
lists:foreach(fun(Key) -> ets:delete(imetrics_counters, Key) end, Keys),
ok
end
).
Expand Down Expand Up @@ -482,11 +493,24 @@ get_mapped_counters() ->
Dict = lists:foldl(fun get_mapped_/2, orddict:new(), get_counter_points()),
orddict:to_list(Dict).

%% Sum by shard first, then convert {Name, Tags} to binary and sum again.
-spec get_counter_points() -> [{map(), integer()}].
get_counter_points() ->
Sums = ets:foldl(fun({{TagsWithName, _Shard}, Value}, Acc) ->
maps:update_with(TagsWithName, fun(Sum) -> Sum + Value end, Value, Acc)
end, #{}, imetrics_counters),
RawSums = ets:foldl(fun({{Series, _Shard}, Value}, Acc) ->
maps:update_with(Series, fun(Sum) -> Sum + Value end, Value, Acc)
end, #{}, imetrics_counters),
{Sums, Malformed} = maps:fold(fun({Name, Tags} = Series, Value, {Acc, Bad}) ->
try imetrics_utils:bin(Tags#{ name => Name }) of
TagsWithName ->
{maps:update_with(TagsWithName, fun(Sum) -> Sum + Value end, Value, Acc), Bad}
catch
error:_ -> {Acc, [Series | Bad]}
end
end, {#{}, []}, RawSums),

% Remove bad counters and record exemplar
discard_counters(Malformed),

lists:sort(maps:to_list(Sums)).

% handle metrics with a function
Expand Down Expand Up @@ -592,3 +616,33 @@ tock_s_name_match(Ticks, Name) ->
MapMatchFun({__K, __V, I2}) ->
MapMatchFun(maps:next(I2))
end(maps:next(I)).

-spec discard_counters([{term(), map()}]) -> ok.
discard_counters([]) ->
ok;
discard_counters([First | _] = Series) ->
NSched = erlang:system_info(schedulers),
[ets:delete(imetrics_counters, {S, Shard}) || S <- Series, Shard <- lists:seq(1, NSched)],

add(imetrics_discarded_series, length(Series)),
try
DLabel = key_label(First),
set_exemplar(imetrics_discarded_series, length(Series), #{key => DLabel}),
ok
catch
_:_ ->
% should not be reachable, but provided for safety
ok
end.

%% The key printed to a bounded depth, as ASCII without the characters that
%% can't appear in an exposition label value, cut to 100 characters so the
%% exemplar's labels stay within the 128 characters the format allows.
-spec key_label(term()) -> binary().
key_label(Series) ->
Printed = lists:flatten(io_lib:format("~tP", [Series, 10])),
Safe = [case C of
_ when C >= 32, C < 127, C =/= $", C =/= $\\ -> C;
_ -> $?
end || C <- lists:sublist(Printed, 100)],
list_to_binary(Safe).
1 change: 1 addition & 0 deletions src/imetrics_app.erl
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
%% ===================================================================

start(_StartType, _StartArgs) ->
persistent_term:put({imetrics, separator}, application:get_env(imetrics, separator, <<"_">>)),
imetrics_sup:start_link().

stop(_State) ->
Expand Down
2 changes: 1 addition & 1 deletion src/imetrics_utils.erl
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ bin(V) when is_integer(V) ->
bin(T) when is_tuple(T) andalso tuple_size(T) =< 8 ->
L = tuple_to_list(T),
L2 = [ bin(X) || X <- L ],
binary_join(L2, application:get_env(imetrics, separator, <<"_">>));
binary_join(L2, persistent_term:get({imetrics, separator}, <<"_">>));
bin(M) when is_map(M) ->
% Surprising finding: previous code using maps:map with an anonymous function
% performs measurably worse on OTP <= 26 due to the repeated creation of the
Expand Down
84 changes: 82 additions & 2 deletions test/imetrics_shard_tests.erl
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ shard_test_() ->
fun histogram_reset/1,
fun delete/1,
fun restart_clears/1,
fun raw_keys/1,
fun discard_exemplar_nasty/1,
fun discard_exemplar_unicode/1,
fun discard_exemplar_huge/1,
fun shard_rows/1,
fun exemplars/1,
fun hist_get_all/1,
Expand Down Expand Up @@ -149,7 +153,7 @@ delete(_) ->
Hist = imetrics_hist_openmetrics:get_all(),
[
?_assertEqual(undefined, proplists:get_value(<<"del_c">>, imetrics:get_with_types())),
?_assertEqual(0, shard_rows(imetrics_counters, imetrics_utils:bin(#{name => del_c, k => v}))),
?_assertEqual(0, shard_rows(imetrics_counters, {del_c, #{k => v}})),
?_assertEqual({counter, [{#{k => <<"v">>}, 1}]}, proplists:get_value(<<"del_keep">>, imetrics:get_with_types())),
?_assertEqual([], imetrics_hist_openmetrics:get_hist(del_h)),
?_assertEqual(0, shard_rows(imetrics_hist_counts, {imetrics_utils:bin(#{'__name__' => del_h}), 1})),
Expand All @@ -160,6 +164,82 @@ delete(_) ->
?_assertEqual(undefined, proplists:get_value(<<"del_h">>, imetrics_hist_openmetrics:get_all()))
].

%% Counter keys are stored raw and converted on read. Raw keys that convert to
%% the same binaries are one series; a key that doesn't convert is stored, then
%% discarded by the next read and counted in imetrics_discarded_series;
%% delete_counter/2 removes every raw form of a series.
raw_keys(_) ->
imetrics:add(raw_c, #{k => v}),
imetrics:add(raw_c, #{k => "v"}),
imetrics:add("raw_c", #{k => <<"v">>}),
imetrics:add_m(raw_m, key),
imetrics:add_m(<<"raw_m">>, "key", 2),
Bad = {a,b,c,d,e,f,g,h,i},
BadResult = imetrics:add(Bad, #{k => v}),
imetrics:add(raw_d, #{k => v}),
imetrics:add(raw_d, #{k => "v"}),
imetrics:add(raw_keep, #{k => v}),
ok = imetrics:delete_counter(raw_d, #{k => <<"v">>}),
imetrics:add_m(raw_t, {a, b}),
BadKeyResult = imetrics:add_m(raw_bad, Bad),
BadRows = fun(Name) -> ets:select_count(imetrics_counters,
[{{{{'$1', '_'}, '_'}, '_'}, [{'=:=', '$1', {const, Name}}], [true]}]) end,
BadBefore = {BadRows(Bad), BadRows(raw_bad)},
Types = imetrics:get_with_types(),
% the malformed series are gone after one read, and later reads don't count them again
Discarded = proplists:get_value(<<"imetrics_discarded_series">>, imetrics:get_with_types()),
DiscardedAgain = proplists:get_value(<<"imetrics_discarded_series">>, imetrics:get_with_types()),
[
?_assertMatch({N, M} when N > 0 andalso M > 0, BadBefore),
?_assertEqual({counter, [{#{}, 2}]}, Discarded),
?_assertEqual(Discarded, DiscardedAgain),
?_assertEqual({0, 0}, {BadRows(Bad), BadRows(raw_bad)}),
?_assertEqual({counter, [{#{k => <<"v">>}, 3}]}, proplists:get_value(<<"raw_c">>, Types)),
?_assertEqual({counter, [{#{map_key => <<"key">>}, 3}]}, proplists:get_value(<<"raw_m">>, Types)),
?_assert(is_integer(BadResult)),
?_assertEqual(undefined, proplists:get_value(<<"raw_d">>, Types)),
?_assertEqual(0, ets:select_count(imetrics_counters,
[{{{{'$1', '_'}, '_'}, '_'}, [{'=:=', '$1', {const, raw_d}}], [true]}])),
?_assertEqual({counter, [{#{k => <<"v">>}, 1}]}, proplists:get_value(<<"raw_keep">>, Types)),
?_assertEqual({counter, [{#{map_key => <<"a_b">>}, 1}]}, proplists:get_value(<<"raw_t">>, Types)),
?_assert(is_integer(BadKeyResult)),
?_assertEqual(undefined, proplists:get_value(<<"raw_bad">>, Types))
].

%% A discarded key is shown as the exemplar of imetrics_discarded_series, for
%% finding where it came from: printable ASCII without the characters a label
%% value can't hold, at most 100 long, and the exposition stays valid.
discard_exemplar_nasty(_) ->
Key = discarded_exemplar_key({"quote\" backslash\\ newline\n \x{e9}", b, c, d, e, f, g, h, i}),
[?_assertNotEqual(nomatch, string:find(Key, "quote")),
?_assert(is_label_safe(Key))].

discard_exemplar_unicode(_) ->
Key = discarded_exemplar_key({"\x{1F600}\x{4e2d}\x{6587}", <<"\x{e9}"/utf8>>, c, d, e, f, g, h, i}),
[?_assert(Key =/= ""),
?_assert(is_label_safe(Key))].

discard_exemplar_huge(_) ->
Key = discarded_exemplar_key({binary:copy(<<"x">>, 100000), b, c, d, e, f, g, h, i}),
[?_assert(Key =/= ""),
?_assert(is_label_safe(Key))].

%% Writes a key that can't be converted, reads once (which discards it and sets
%% the exemplar), then returns the exemplar's label value from a /metrics scrape.
discarded_exemplar_key(BadName) ->
application:set_env(imetrics, openmetrics_exemplar_compat, true),
imetrics:add(BadName, #{k => v}),
_ = imetrics:get_counters(),
Body = http_get("/metrics"),
application:unset_env(imetrics, openmetrics_exemplar_compat),
{match, [Key]} = re:run(Body, "imetrics_discarded_series_total\\{\\} 1 # \\{key=\"([^\"]*)\"\\} 1 ",
[{capture, all_but_first, list}]),
Key.

is_label_safe(Key) ->
length(Key) =< 100 andalso
lists:all(fun(C) -> C >= 32 andalso C < 127 andalso C =/= $" andalso C =/= $\\ end, Key).

%% Restarting imetrics recreates its tables, dropping every shard.
restart_clears(_) ->
par(fun() -> imetrics:add(restart_c) end),
Expand All @@ -175,7 +255,7 @@ shard_rows(_) ->
pinned(fun() -> imetrics_hist_openmetrics:add(rows_h, 0) end),
Shards = lists:seq(1, erlang:system_info(schedulers_online)),
[
?_assertEqual(Shards, shard_ids(imetrics_counters, imetrics_utils:bin(#{name => rows_c, k => v}))),
?_assertEqual(Shards, shard_ids(imetrics_counters, {rows_c, #{k => v}})),
?_assertEqual(Shards, shard_ids(imetrics_hist_counts, {imetrics_utils:bin(#{'__name__' => rows_h}), 1}))
].

Expand Down
37 changes: 26 additions & 11 deletions test/imetrics_tests.erl
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ add_test(_Fixture) ->
?_assertEqual(5, proplists:get_value(<<"many_incr">>, imetrics:get_counters())),
?_assertEqual(1, imetrics:add({a,b,c})),
?_assertEqual(1, imetrics:add(200)),
?_assertEqual({error,{function_clause,check_inputs}}, imetrics:add({a,b,c,d,e,f,g,h,i})),
% not checked on write; a key that doesn't convert is left out of reads
?_assert(is_integer(imetrics:add({a,b,c,d,e,f,g,h,i}))),
?_assertEqual({error,{badmatch,check_inputs}}, imetrics:add(bad, map))
].

Expand Down Expand Up @@ -185,6 +186,30 @@ init_counter_test(_Fixture) ->
))
].

%% the separator is read once, when the application starts
separator_test_() ->
{setup,
fun() ->
application:load(imetrics),
application:set_env(imetrics, http_server_port, 8086),
application:set_env(imetrics, separator, <<":">>),
application:ensure_all_started(imetrics),
#{}
end,
fun(Fixture) ->
stop(Fixture),
application:unset_env(imetrics, separator)
end,
fun(_Fixture) ->
imetrics:add({counter, tuple, colon}),
imetrics:add_m(mapped_colon, {key, tuple}),
[
?_assertEqual(<<"a:b">>, imetrics_utils:bin({a, b})),
?_assertEqual({counter, [{#{}, 1}]}, proplists:get_value(<<"counter:tuple:colon">>, imetrics:get_with_types())),
?_assertEqual({counter, [{#{map_key => <<"key:tuple">>}, 1}]}, proplists:get_value(<<"mapped_colon">>, imetrics:get_with_types()))
]
end}.

%% get tests
get_test_() ->
{setup,
Expand All @@ -203,9 +228,6 @@ start_get() ->
imetrics:set_gauge(fn_gauge, fun() -> 1.5 end),
imetrics:set_gauge(fn_gauge_timeout, fun() -> timer:sleep(6000), 1 end),
imetrics:add({counter, tuple}),
application:set_env(imetrics, separator, <<":">>),
imetrics:add({counter, tuple, colon}),
application:unset_env(imetrics, separator),
Stats = imetrics:stats(stats),
Stats2 = imetrics_stats:update(10, Stats),
imetrics:set_stats(stats, Stats2),
Expand Down Expand Up @@ -313,7 +335,6 @@ http_test_varz(#{port := Port}) ->
"counter2 1",
"counter3_invalid_exemplar 1",
"counter4_invalid_exemplar 1",
"counter:tuple:colon 1",
"counter_tuple 1",
"mapped_counter key:1",
"fn_gauge 1.5",
Expand Down Expand Up @@ -343,8 +364,6 @@ http_test_openmetrics(#{port := Port}) ->
"counter3_invalid_exemplar{} 1",
"# TYPE counter4_invalid_exemplar counter",
"counter4_invalid_exemplar{} 1",
"# TYPE counter:tuple:colon counter",
"counter:tuple:colon{} 1",
"# TYPE counter_tuple counter",
"counter_tuple{} 1",
"# TYPE imetrics_metric_fun_timeout counter",
Expand Down Expand Up @@ -452,8 +471,6 @@ http_test_openmetrics_strict(#{port := Port}) ->
"counter3_invalid_exemplar{} 1",
"# TYPE counter4_invalid_exemplar counter",
"counter4_invalid_exemplar{} 1",
"# TYPE counter:tuple:colon counter",
"counter:tuple:colon{} 1",
"# TYPE counter_tuple counter",
"counter_tuple{} 1",
"# TYPE imetrics_metric_fun_timeout counter",
Expand Down Expand Up @@ -541,8 +558,6 @@ http_test_openmetrics_exemplars(#{port := Port}) ->
"counter3_invalid_exemplar_total{} 1",
"# TYPE counter4_invalid_exemplar counter",
"counter4_invalid_exemplar_total{} 1",
"# TYPE counter:tuple:colon counter",
"counter:tuple:colon_total{} 1",
"# TYPE counter_tuple counter",
"counter_tuple_total{} 1",
"# TYPE imetrics_metric_fun_timeout counter",
Expand Down
Loading