/
memory_monitor.sh
executable file
·60 lines (53 loc) · 2.66 KB
/
memory_monitor.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/bin/sh
user=$1
password=$2
host=$3
threshold=${4:-2147483648}
curl -X POST -u $user:$password http://$host/diag/eval -d @- <<EOF
rpc:eval_everywhere(
proc_lib, spawn,
[ fun () ->
case whereis(memory_monitor) of
undefined ->
ok;
Pid ->
error_logger:info_msg("Killing old memory monitor ~p", [Pid]),
catch exit(Pid, kill),
misc:wait_for_process(Pid, infinity)
end,
erlang:register(memory_monitor, self()),
Threshold = ${threshold},
error_logger:info_msg("Memory monitor started (pid ~p, threshold ~p)", [self(), Threshold]),
Loop = fun (Recur) ->
Total = erlang:memory(total),
case Total > Threshold of
true ->
catch error_logger:info_msg("Total used memory ~p exceeded threshold ~p", [Total, Threshold]),
catch ale:sync_all_sinks(),
lists:foreach(
fun (Pid) ->
try diag_handler:grab_process_info(Pid) of
V ->
BinBefore = proplists:get_value(binary, erlang:memory()),
Res = (catch begin erlang:garbage_collect(Pid), erlang:garbage_collect(Pid), erlang:garbage_collect(Pid), erlang:garbage_collect(Pid), nothing end),
BinAfter = proplists:get_value(binary, erlang:memory()),
PList = V ++ [{binary_diff, BinAfter - BinBefore}, {res, Res}],
error_logger:info_msg("Process ~p~n~p", [Pid, PList])
catch _:_ ->
ok
end
end, erlang:processes()),
error_logger:info_msg("Done. Going to die"),
gen_event:which_handlers(error_logger),
catch ale:sync_all_sinks(),
erlang:halt("memory_monitor");
false ->
catch error_logger:info_msg("Current total memory used ~p", [Total]),
ok
end,
timer:sleep(5000),
Recur(Recur)
end,
Loop(Loop)
end ]).
EOF