Welcome to mirror list, hosted at ThFree Co, Russian Federation.

p1_prof.erl « src - github.com/processone/ejabberd.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d4f4b885671a662742f9567eed8d6fc38b9d4998 (plain)
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
%%%-------------------------------------------------------------------
%%% File    : p1_prof.erl
%%% Author  : Evgeniy Khramtsov <ekhramtsov@process-one.net>
%%% Description : Handy wrapper around eprof and fprof
%%%
%%% Created : 23 Jan 2010 by Evgeniy Khramtsov <ekhramtsov@process-one.net>
%%%
%%%
%%% ejabberd, Copyright (C) 2002-2013   ProcessOne
%%%
%%% This program is free software; you can redistribute it and/or
%%% modify it under the terms of the GNU General Public License as
%%% published by the Free Software Foundation; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
%%% General Public License for more details.
%%%
%%% You should have received a copy of the GNU General Public License
%%% along with this program; if not, write to the Free Software
%%% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
%%% 02111-1307 USA
%%%
%%%-------------------------------------------------------------------
-module(p1_prof).

%% API
-export([eprof_start/0, eprof_stop/0,
	 fprof_start/0, fprof_start/1,
	 fprof_stop/0, fprof_analyze/0,
	 queue/0, queue/1, memory/0, memory/1,
	 reds/0, reds/1, trace/1, help/0,
	 q/0, m/0, r/0, q/1, m/1, r/1]).

-define(APPS, [ejabberd, mnesia]).

%%====================================================================
%% API
%%====================================================================
eprof_start() ->
    eprof:start(),
    case lists:keyfind(running, 1, application:info()) of
	{_, Apps} ->
	    case get_procs(?APPS, Apps) of
		[] ->
		    {error, no_procs_found};
		Procs ->
		    eprof:start_profiling(Procs)
	    end;
	_ ->
	    {error, no_app_info}
    end.

fprof_start() ->
    fprof_start(0).

fprof_start(Duration) ->
    case lists:keyfind(running, 1, application:info()) of
	{_, Apps} ->
	    case get_procs(?APPS, Apps) of
		[] ->
		    {error, no_procs_found};
		Procs ->
		    fprof:trace([start, {procs, Procs}]),
		    io:format("Profiling started~n"),
		    if Duration > 0 ->
			    timer:sleep(Duration*1000),
			    fprof:trace([stop]),
			    fprof:stop();
		       true->
			    ok
		    end
	    end;
	_ ->
	    {error, no_app_info}
    end.

fprof_stop() ->
    fprof:trace([stop]),
    fprof:profile(),
    fprof:analyse([totals, no_details, {sort, own},
		   no_callers, {dest, "fprof.analysis"}]),
    fprof:stop(),
    format_fprof_analyze().

fprof_analyze() ->
    fprof_stop().

eprof_stop() ->
    eprof:stop_profiling(),
    case erlang:function_exported(eprof, analyse, 0) of
	true ->
	    eprof:analyse();
	false ->
	    eprof:analyze()
    end.

help() ->
    M = ?MODULE,
    io:format("Brief help:~n"
	      "~p:queue(N) - show top N pids sorted by queue length~n"
	      "~p:queue() - shorthand for ~p:queue(10)~n"
	      "~p:memory(N) - show top N pids sorted by memory usage~n"
	      "~p:memory() - shorthand for ~p:memory(10)~n"
	      "~p:reds(N) - show top N pids sorted by reductions~n"
	      "~p:reds() - shorthand for ~p:reds(10)~n"
	      "~p:q(N)|~p:q() - same as ~p:queue(N)|~p:queue()~n"
	      "~p:m(N)|~p:m() - same as ~p:memory(N)|~p:memory()~n"
	      "~p:r(N)|~p:r() - same as ~p:reds(N)|~p:reds()~n"
	      "~p:trace(Pid) - trace Pid; to stop tracing close "
	      "Erlang shell with Ctrl+C~n"
	      "~p:eprof_start() - start eprof on all available pids; "
	      "DO NOT use on production system!~n"
	      "~p:eprof_stop() - stop eprof and print result~n"
	      "~p:fprof_start() - start fprof on all available pids; "
	      "DO NOT use on production system!~n"
	      "~p:fprof_stop() - stop eprof and print formatted result~n"
	      "~p:fprof_start(N) - start and run fprof for N seconds; "
	      "use ~p:fprof_analyze() to analyze collected statistics and "
	      "print formatted result; use on production system with CARE~n"
	      "~p:fprof_analyze() - analyze previously collected statistics "
	      "using ~p:fprof_start(N) and print formatted result~n"
	      "~p:help() - print this help~n",
	      lists:duplicate(31, M)).

q() ->
    queue().

q(N) ->
    queue(N).

m() ->
    memory().

m(N) ->
    memory(N).

r() ->
    reds().

r(N) ->
    reds(N).

queue() ->
    queue(10).

memory() ->
    memory(10).

reds() ->
    reds(10).

queue(N) ->
    dump(N, lists:reverse(lists:ukeysort(1, all_pids(queue)))).

memory(N) ->
    dump(N, lists:reverse(lists:ukeysort(3, all_pids(memory)))).

reds(N) ->
    dump(N, lists:reverse(lists:ukeysort(4, all_pids(reductions)))).

trace(Pid) ->
    erlang:trace(Pid, true, [send, 'receive']),
    trace_loop().

trace_loop() ->
    receive
	M ->
	    io:format("~p~n", [M]),
	    trace_loop()
    end.

%%====================================================================
%% Internal functions
%%====================================================================
get_procs(Apps, AppList) ->
    io:format("Searching for processes to profile...~n", []),
    Procs = lists:flatmap(
	      fun({App, Leader}) when is_pid(Leader) ->
		      case lists:member(App, Apps) of
			  true ->
			      get_procs(Leader);
			  false ->
			      []
		      end;
		 (_) ->
		      []
	      end, AppList),
    io:format("Found ~p processes~n", [length(Procs)]),
    Procs.

get_procs(Leader) ->
    lists:filter(
      fun(Pid) ->
	      case process_info(Pid, group_leader) of
		  {_, Leader} ->
		      true;
		  _ ->
		      false
	      end
      end, processes()).

format_fprof_analyze() ->
    case file:consult("fprof.analysis") of
	{ok, [_, [{totals, _, _, TotalOWN}] | Rest]} ->
	    OWNs = lists:flatmap(
		     fun({MFA, _, _, OWN}) ->
			     Percent = OWN*100/TotalOWN,
			     case round(Percent) of
				 0 ->
				     [];
				 _ ->
				     [{mfa_to_list(MFA), Percent}]
			     end
		     end, Rest),
	    ACCs = collect_accs(Rest),
	    MaxACC = find_max(ACCs),
	    MaxOWN = find_max(OWNs),
	    io:format("=== Sorted by OWN:~n"),
	    lists:foreach(
	      fun({MFA, Per}) ->
		      L = length(MFA),
		      S = lists:duplicate(MaxOWN - L + 2, $ ),
		      io:format("~s~s~.2f%~n", [MFA, S, Per])
	      end, lists:reverse(lists:keysort(2, OWNs))),
	    io:format("~n=== Sorted by ACC:~n"),
	    lists:foreach(
	      fun({MFA, Per}) ->
		      L = length(MFA),
		      S = lists:duplicate(MaxACC - L + 2, $ ),
		      io:format("~s~s~.2f%~n", [MFA, S, Per])
	      end, lists:reverse(lists:keysort(2, ACCs)));
	Err ->
	    Err
    end.

mfa_to_list({M, F, A}) ->
    atom_to_list(M) ++ ":" ++ atom_to_list(F) ++ "/" ++ integer_to_list(A);
mfa_to_list(F) when is_atom(F) ->
    atom_to_list(F).

find_max(List) ->
    find_max(List, 0).

find_max([{V, _}|Tail], Acc) ->
    find_max(Tail, lists:max([length(V), Acc]));
find_max([], Acc) ->
    Acc.

collect_accs(List) ->
    List1 = lists:filter(
	      fun({MFA, _, _, _}) ->
		      case MFA of
			  {sys, _, _} ->
			      false;
			  suspend ->
			      false;
			  {gen_fsm, _, _} ->
			      false;
			  {p1_fsm, _, _} ->
			      false;
			  {gen, _, _} ->
			      false;
			  {gen_server, _, _} ->
			      false;
			  {proc_lib, _, _} ->
			      false;
			  _ ->
			      true
		      end
	      end, List),
    TotalACC = lists:sum([A || {_, _, A, _} <- List1]),
    lists:flatmap(
      fun({MFA, _, ACC, _}) ->
	      Percent = ACC*100/TotalACC,
	      case round(Percent) of
		  0 ->
		      [];
		  _ ->
		      [{mfa_to_list(MFA), Percent}]
	      end
      end, List1).

all_pids(Type) ->
    lists:foldl(
      fun(P, Acc) when P == self() ->
	      %% exclude ourself from statistics
	      Acc;
	 (P, Acc) ->
	      case catch process_info(
			   P,
			   [message_queue_len,
			    memory,
			    reductions,
			    dictionary,
			    current_function,
			    registered_name]) of
		  [{_, Len}, {_, Memory}, {_, Reds},
		   {_, Dict}, {_, CurFun}, {_, RegName}] ->
                      IntQLen = case lists:keysearch('$internal_queue_len', 1, Dict) of
                                    {value, {_, N}} ->
                                        N;
                                    _ ->
                                        0
                                end,
		      if Type == queue andalso Len == 0 andalso IntQLen == 0 ->
			      Acc;
			 true ->
                              MaxLen = lists:max([Len, IntQLen]),
			      [{MaxLen, Len, Memory, Reds, Dict, CurFun, P, RegName}|Acc]
		      end;
		  _ ->
		      Acc
	      end
      end, [], processes()).

dump(N, Rs) ->
    lists:foreach(
      fun({_, MsgQLen, Memory, Reds, Dict, CurFun, Pid, RegName}) ->
	      PidStr = pid_to_list(Pid),
	      [_, Maj, Min] = string:tokens(
				string:substr(
				  PidStr, 2, length(PidStr) - 2), "."),
              io:format("** pid(0,~s,~s)~n"
			"** registered name: ~p~n"
			"** memory: ~p~n"
			"** reductions: ~p~n"
                        "** message queue len: ~p~n"
			"** current_function: ~p~n"
                        "** dictionary: ~p~n~n",
                        [Maj, Min, RegName, Memory, Reds, MsgQLen, CurFun, Dict])
      end, nthhead(N, Rs)).

nthhead(N, L) ->
    lists:reverse(nthhead(N, L, [])).

nthhead(0, _L, Acc) ->
    Acc;
nthhead(N, [H|T], Acc) ->
    nthhead(N-1, T, [H|Acc]);
nthhead(_N, [], Acc) ->
    Acc.