aboutsummaryrefslogtreecommitdiffstats
path: root/lib/percept/src/percept.erl
blob: f30c1dd585e106f85e003bdb6ee0fe47936a5831 (plain) (blame)
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
%%
%% %CopyrightBegin%
%% 
%% Copyright Ericsson AB 2007-2009. All Rights Reserved.
%% 
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at http://www.erlang.org/.
%% 
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%% 
%% %CopyrightEnd%
%% 

%% 
%% @doc Percept - Erlang Concurrency Profiling Tool
%%
%%	This module provides the user interface for the application.
%% 

-module(percept).
-behaviour(application).
-export([
	profile/1, 
	profile/2, 
	profile/3,
	stop_profile/0, 
	start_webserver/0, 
	start_webserver/1, 
	stop_webserver/0, 
	stop_webserver/1, 
	analyze/1,
	% Application behaviour
	start/2, 
	stop/1]).


-include("percept.hrl").

%%==========================================================================
%%
%% 		Type definitions 
%%
%%==========================================================================

%% @type percept_option() = procs | ports | exclusive

-type percept_option() :: 'procs' | 'ports' | 'exclusive' | 'scheduler'.

%%==========================================================================
%%
%% 		Application callback functions
%%
%%==========================================================================

%% @spec start(Type, Args) -> {started, Hostname, Port} | {error, Reason} 
%% @doc none
%% @hidden

start(_Type, _Args) ->
    %% start web browser service
    start_webserver(0).

%% @spec stop(State) -> ok 
%% @doc none
%% @hidden

stop(_State) ->
    %% stop web browser service
    stop_webserver(0).

%%==========================================================================
%%
%% 		Interface functions
%%
%%==========================================================================

%% @spec profile(Filename::string()) -> {ok, Port} | {already_started, Port}
%% @see percept_profile

%% profiling

-spec profile(Filename :: file:filename()) ->
	{'ok', port()} | {'already_started', port()}.

profile(Filename) ->
    percept_profile:start(Filename, [procs]).

%% @spec profile(Filename::string(), [percept_option()]) -> {ok, Port} | {already_started, Port}
%% @see percept_profile

-spec profile(Filename :: file:filename(),
	      Options :: [percept_option()]) ->
	{'ok', port()} | {'already_started', port()}.

profile(Filename, Options) ->
    percept_profile:start(Filename, Options). 

%% @spec profile(Filename::string(), MFA::mfa(), [percept_option()]) -> ok | {already_started, Port} | {error, not_started}
%% @see percept_profile

-spec profile(Filename :: file:filename(),
	      Entry :: {atom(), atom(), list()},
	      Options :: [percept_option()]) ->
	'ok' | {'already_started', port()} | {'error', 'not_started'}.

profile(Filename, MFA, Options) ->
    percept_profile:start(Filename, MFA, Options).

-spec stop_profile() -> 'ok' | {'error', 'not_started'}.

%% @spec stop_profile() -> ok | {'error', 'not_started'}
%% @see percept_profile

stop_profile() ->
    percept_profile:stop().

%% @spec analyze(string()) -> ok | {error, Reason} 
%% @doc Analyze file.

-spec analyze(Filename :: file:filename()) ->
	'ok' | {'error', any()}.

analyze(Filename) ->
    case percept_db:start() of 
	{started, DB} ->
	    parse_and_insert(Filename,DB);
	{restarted, DB} ->
	    parse_and_insert(Filename,DB)
    end.

%% @spec start_webserver() -> {started, Hostname, Port} | {error, Reason}
%%	Hostname = string()
%%	Port = integer()
%%	Reason = term() 
%% @doc Starts webserver.

-spec start_webserver() ->
	{'started', string(), pos_integer()} | {'error', any()}.

start_webserver() ->
    start_webserver(0).

%% @spec start_webserver(integer()) -> {started, Hostname, AssignedPort} | {error, Reason}
%%	Hostname = string()
%%	AssignedPort = integer()
%%	Reason = term() 
%% @doc Starts webserver. If port number is 0, an available port number will 
%%	be assigned by inets.

-spec start_webserver(Port :: non_neg_integer()) ->
	{'started', string(), pos_integer()} | {'error', any()}.

start_webserver(Port) when is_integer(Port) ->
    application:load(percept),
    case whereis(percept_httpd) of
	undefined ->
	    {ok, Config} = get_webserver_config("percept", Port),
	    inets:start(),
	    case inets:start(httpd, Config) of
		{ok, Pid} ->
		    AssignedPort = find_service_port_from_pid(inets:services_info(), Pid),
		    {ok, Host} = inet:gethostname(),
		    %% workaround until inets can get me a service from a name.
		    Mem = spawn(fun() -> service_memory({Pid,AssignedPort,Host}) end),
		    register(percept_httpd, Mem),
		    {started, Host, AssignedPort};
		{error, Reason} ->
		    {error, {inets, Reason}}
	   end;
	_ ->
	    {error, already_started}
    end.

%% @spec stop_webserver() -> ok | {error, not_started}  
%% @doc Stops webserver.

stop_webserver() ->
    case whereis(percept_httpd) of
    	undefined -> 
	    {error, not_started};
	Pid ->
	    Pid ! {self(), get_port},
	    receive Port -> ok end,
	    Pid ! quit,
	    stop_webserver(Port)
    end.

%% @spec stop_webserver(integer()) -> ok | {error, not_started}
%% @doc Stops webserver of the given port.
%% @hidden

stop_webserver(Port) ->
    case find_service_pid_from_port(inets:services_info(), Port) of
	undefined ->
	    {error, not_started};
	Pid ->
	    inets:stop(httpd, Pid)
    end. 

%%==========================================================================
%%
%% 		Auxiliary functions 
%%
%%==========================================================================

%% parse_and_insert

parse_and_insert(Filename, DB) ->
    io:format("Parsing: ~p ~n", [Filename]),
    T0 = erlang:now(),
    Pid = dbg:trace_client(file, Filename, mk_trace_parser(self())),
    Ref = erlang:monitor(process, Pid), 
    parse_and_insert_loop(Filename, Pid, Ref, DB, T0).

parse_and_insert_loop(Filename, Pid, Ref, DB, T0) ->
    receive
	{'DOWN',Ref,process, Pid, noproc} ->
	    io:format("Incorrect file or malformed trace file: ~p~n", [Filename]),
	    {error, file};
    	{parse_complete, {Pid, Count}} ->
	    receive {'DOWN', Ref, process, Pid, normal} -> ok after 0 -> ok end,
	    DB ! {action, consolidate},
	    T1 = erlang:now(),
	    io:format("Parsed ~p entries in ~p s.~n", [Count, ?seconds(T1, T0)]),
    	    io:format("    ~p created processes.~n", [length(percept_db:select({information, procs}))]),
     	    io:format("    ~p opened ports.~n", [length(percept_db:select({information, ports}))]),
	    ok;
	{'DOWN',Ref, process, Pid, normal} -> parse_and_insert_loop(Filename, Pid, Ref, DB, T0);
	{'DOWN',Ref, process, Pid, Reason} -> {error, Reason}
    end.

mk_trace_parser(Pid) -> 
    {fun trace_parser/2, {0, Pid}}.

trace_parser(end_of_trace, {Count, Pid}) -> 
    Pid ! {parse_complete, {self(),Count}},
    receive
	{ack, Pid} -> 
	    ok
    end;
trace_parser(Trace, {Count, Pid}) ->
    percept_db:insert(Trace),
    {Count + 1,  Pid}.

find_service_pid_from_port([], _) ->
    undefined;
find_service_pid_from_port([{_, Pid, Options} | Services], Port) ->
    case lists:keyfind(port, 1, Options) of
	false ->
	    find_service_pid_from_port(Services, Port);
	{port, Port} ->
	    Pid
    end.

find_service_port_from_pid([], _) ->
    undefined;
find_service_port_from_pid([{_, Pid, Options} | _], Pid) ->
    case lists:keyfind(port, 1, Options) of
	false ->
	    undefined;
	{port, Port} ->
	   Port
    end;
find_service_port_from_pid([{_, _, _} | Services], Pid) ->
    find_service_port_from_pid(Services, Pid).
    
%% service memory

service_memory({Pid, Port, Host}) ->
    receive
	quit -> 
	    ok;
	{Reply, get_port} ->
	    Reply ! Port,
	    service_memory({Pid, Port, Host});
	{Reply, get_host} -> 
	    Reply ! Host,
	    service_memory({Pid, Port, Host});
	{Reply, get_pid} -> 
	    Reply ! Pid,
	    service_memory({Pid, Port, Host})
    end.

% Create config data for the webserver 

get_webserver_config(Servername, Port) when is_list(Servername), is_integer(Port) ->
    Path = code:priv_dir(percept),
    Root = filename:join([Path, "server_root"]),
    MimeTypesFile = filename:join([Root,"conf","mime.types"]),
    {ok, MimeTypes} = httpd_conf:load_mime_types(MimeTypesFile),
    Config = [
	% Roots
	{server_root, Root},
	{document_root,filename:join([Root, "htdocs"])},
	
	% Aliases
	{eval_script_alias,{"/eval",[io]}},
	{erl_script_alias,{"/cgi-bin",[percept_graph,percept_html,io]}},
	{script_alias,{"/cgi-bin/", filename:join([Root, "cgi-bin"])}},
	{alias,{"/javascript/",filename:join([Root, "scripts"]) ++ "/"}},
	{alias,{"/images/", filename:join([Root, "images"]) ++ "/"}},
	{alias,{"/css/", filename:join([Root, "css"]) ++ "/"}},
	
	% Logs
	%{transfer_log, filename:join([Path, "logs", "transfer.log"])},
	%{error_log, filename:join([Path, "logs", "error.log"])},
	
	% Configs
	{default_type,"text/plain"},
	{directory_index,["index.html"]},
	{mime_types, MimeTypes},
	{modules,[mod_alias,
	          mod_esi,
	          mod_actions,
	          mod_cgi,
	          mod_include,
	          mod_dir,
	          mod_get,
	          mod_head
	%          mod_log,
	%          mod_disk_log
	]},
	{com_type,ip_comm},
	{server_name, Servername},
	{bind_address, any},
	{port, Port}],
    {ok, Config}.