1 -module(rails_connection_pool
).
5 %% Convenience Function
6 simple_handle_request(Arg
,ServerInfo
) ->
7 {Source
, Resource
} = rails_connection_pool:get(),
8 Response
= rails_forwarder:handle_request(Resource
, Arg
, ServerInfo
, 10000),
9 rails_connection_pool:refund({Source
,Resource
}),
13 handle_request(Arg
,ServerInfo
) ->
14 handle_request_helper(Arg
,ServerInfo
,0).
16 handle_request_helper(_Arg
,_ServerInfo
,Retries
) when Retries
> 1 ->
18 handle_request_helper(Arg
,ServerInfo
,Retries
) ->
19 Remote
= fun(A
,S
,Target
) ->
20 {Source
, Handler
} = rails_connection_pool:get(),
21 Response
= rails_forwarder:rails_handle_request(Handler
, A
, S
, 10000),
22 Target
! {rails_response
, Response
},
23 rails_connection_pool:refund({Source
, Handler
}) end,
24 _RequestProc
= spawn(Remote(Arg
,ServerInfo
,self())),
26 {rails_response
, Response
} ->
29 handle_request_helper(Arg
,ServerInfo
, Retries
+1)
33 %% Server manipulation
35 global:register_name(?MODULE
, spawn(
37 process_flag(trap_exit
, true
),
38 rails_connection_pool:loop([],[]) end
42 add({Node
, Proc
}) when is_pid(Proc
) ->
43 global:send(?MODULE
, {add
, {Node
, Proc
}}),
47 global:send(?MODULE
, {remove
, Rsrc
}),
51 global:send(?MODULE
, {get, self()}),
58 global:send(?MODULE
, {refund
, Node
}),
62 global:send(?MODULE
, {list, self()}),
69 global:send(?MODULE
, {list_all
, self()}),
75 remove_server(Server
) ->
76 global:send(?MODULE
, {remove_server
, Server
}),
80 global:send(?MODULE
, {remove_all
}),
83 remove_server_filter(Server
, {Server
, _X
}) -> false
;
84 remove_server_filter(_Server
, {_NotServer
, _X
}) -> true
.
88 {add
, {Node
, Proc
}} when is_pid(Proc
) ->
90 loop([{Node
,Proc
}],[{Node
,Proc
}|A
]);
98 Membership
= lists:member(Node
,A
),
105 {'EXIT', Pid
, _Reason
} ->
106 FilterFun
= fun({_Node
,MPid
}) -> MPid
/= Pid
end,
107 loop([],lists:filter(FilterFun
, A
))
111 {add
, {Node
, Proc
}} when is_pid(Proc
)->
116 loop(lists:delete(I
,X
), lists:delete(I
,A
));
117 {remove_server
, Server
} ->
118 PurgedX
= lists:filter(fun(Z
) -> remove_server_filter(Server
, Z
) end, X
),
119 PurgedA
= lists:filter(fun(Z
) -> remove_server_filter(Server
, Z
) end, A
),
120 loop(PurgedX
, PurgedA
);
127 Pid
! {all_nodes
, A
},
134 Membership
= lists:member(Node
,A
),
141 {'EXIT', Pid
, _Reason
} ->
142 FilterFun
= fun({_Node
,MPid
}) -> MPid
/= Pid
end,
143 loop(lists:filter(FilterFun
,X
),lists:filter(FilterFun
, A
));
145 io:format("~p loop(X,A) Received unknown message: ~p~n", [?MODULE
, Other
]),