Skip to content

Instantly share code, notes, and snippets.

@nlinker
Created October 12, 2012 03:47
Show Gist options
  • Save nlinker/3877190 to your computer and use it in GitHub Desktop.
Save nlinker/3877190 to your computer and use it in GitHub Desktop.
Script to check how many connections can Apache server survive
#!/usr/bin/env escript
-mode(compile).
-compile(export_all).
main([]) -> io:format("Usage: ~s URL [Count=1000]~n", [escript:script_name()]);
main([URL]) -> main([URL,"100"]);
main([URL,C] ) -> manage_workers(URL, [start_worker(URL, N) || N <- lists:seq(1,list_to_integer(C))]), ok.
manage_workers(URL, Workers) ->
receive
{'DOWN', _, _, Pid, _} ->
{value, {N,Pid}, W1} = lists:keytake(Pid, 2, Workers),
io:format("Down worker ~p~n", [N]),
timer:sleep(500),
manage_workers(URL, [start_worker(URL, N)|W1])
end.
start_worker(URL, N) ->
{ok, Pid} = proc_lib:start(?MODULE, init_request, [URL, N]),
erlang:monitor(process, Pid),
{N,Pid}.
init_request(URL, N) ->
try run_long_request(URL, N) of
A -> A
catch
Class:Error ->
error_logger:format("~s:~s~n~p~n", [Class, Error, erlang:get_stacktrace()])
end.
run_long_request(URL,N) ->
io:format("Worker ~p on ~s~n", [N, URL]),
proc_lib:init_ack({ok, self()}),
{ok, Socket} = try_connect(URL),
send_long_headers(Socket, N).
try_connect(URL) ->
{ok, {_, _, Host, Port, Path, []}} = http_uri:parse(URL),
case gen_tcp:connect(Host, Port, [binary, {recbuf, 10}]) of
{ok, Socket} ->
ok = gen_tcp:send(Socket, ["GET ", Path, " HTTP/1.1\r\n"
"Host: ", Host, "\r\n"
]),
{ok, Socket};
{error, econnrefused} ->
timer:sleep(1000),
try_connect(URL)
end.
send_long_headers(Socket, N) ->
case gen_tcp:send(Socket, ["X-Header-", integer_to_list(random:uniform(100)), ": value\r\n"]) of
ok -> timer:sleep(990), send_long_headers(Socket, N);
{error, Reason} -> io:format("Closed (~B): ~p~n", [N, Reason])
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment