Skip to content

Commit

Permalink
add memory info CLI support function
Browse files Browse the repository at this point in the history
  • Loading branch information
RoadRunnr authored and mgumz committed May 21, 2019
1 parent 4070302 commit d8af3fb
Showing 1 changed file with 53 additions and 1 deletion.
54 changes: 53 additions & 1 deletion src/ergw_api.erl
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@

-module(ergw_api).

-compile([{parse_transform, cut}]).

%% API
-export([peer/1, tunnel/1, contexts/1, delete_contexts/1]).
-export([peer/1, tunnel/1, contexts/1, delete_contexts/1, memory/1]).

%%%===================================================================
%%% API
Expand Down Expand Up @@ -41,6 +43,13 @@ delete_contexts(Count) ->
Contexts = lists:sublist(contexts(all), Count),
lists:foreach(fun(Pid) -> gtp_context:delete_context(Pid) end, Contexts).

memory(Limit0) ->
Limit = min(Limit0, 100),
ProcInfo = process_info(),
Summary = process_summary(ProcInfo),
LProcS = lists:sublist(lists:reverse(lists:keysort(3, Summary)), Limit),
io:format("~s~n", [fmt_process_summary("ProcessSummary", LProcS)]),
ok.

%%%===================================================================
%%% Internal functions
Expand All @@ -58,3 +67,46 @@ collect_contexts(Context, Tunnels) ->
io:format("Context: ~p~n", [Context]),
Info = gtp_context:info(Context),
[Info#{'Process' => Context} | Tunnels].

units(X) when X > 1024 * 1024 * 1024 ->
io_lib:format("~.4f GB", [X / math:pow(2, 30)]);
units(X) when X > 1024 * 1024 ->
io_lib:format("~.4f MB", [X / math:pow(2, 20)]);
units(X) when X > 1024 ->
io_lib:format("~.4f kB", [X / math:pow(2, 10)]);
units(X) ->
io_lib:format("~.4w byte", [X]).

mfa({M, F, A}) when is_atom(M), is_atom(F), is_integer(A) ->
io_lib:format("~s:~s/~w", [M, F, A]);
mfa(MFA) ->
io_lib:format("~p", [MFA]).

process_info() ->
[begin
{_, C} = erlang:process_info(Pid, current_function),
{_, M} = erlang:process_info(Pid, memory),
I = proc_lib:translate_initial_call(Pid),
{Pid, C, I, M}
end
|| Pid <- erlang:processes()].

upd_process_summary(Mem, {I, Cnt, Sum, Log, Min, Max}) ->
{I, Cnt + 1, Sum + Mem, Log + math:log(Mem), min(Min, Mem), max(Max, Mem)}.

process_summary(ProcInfo) ->
M = lists:foldl(
fun({_Pid, _C, I, M}, Acc) ->
maps:update_with(
I, upd_process_summary(M, _), {I, 1, M, math:log(M), M, M}, Acc)
end, #{}, ProcInfo),
maps:values(M).

fmt_process_summary(Head, Summary) ->
io_lib:format("~s~n~-40.s ~10.s ~15.s ~15.s ~15.s ~15.s ~15.s~n",
[Head, "Initial", "Count", "Total",
"Min", "Max", "Arith. Avg", "Geom. Avg"]) ++
[[io_lib:format("~-40s ~10.w ~15.s ~15.s ~15.s ~15.s ~15.s~n",
[mfa(I), Cnt, units(Sum), units(Min), units(Max),
units(Sum/Cnt), units(math:exp(Log / Cnt))])
|| {I, Cnt, Sum, Log, Min, Max} <- Summary]].

0 comments on commit d8af3fb

Please sign in to comment.