%% %% Load balancer %% %% Author: Krzysztof Kliƛ %% %% 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 3 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, see . %% -module(balancer). -export([load/0, show/1, pick/1]). -define(TIMEOUT, 3000). % Return node() system load. load() -> load_result(cpu_sup:avg1()). load_result(0) -> cpu_sup:start(), {load, node(), cpu_sup:avg1()}; load_result(N) -> {load, node(), N}. % Show load of all nodes show([]) -> show([node()]); show(L) -> {Results, _} = rpc:multicall(L, balancer, load, [], ?TIMEOUT), [{Node, Load} || {load, Node, Load} <- Results]. % Pick a node with lowest system load from list L. pick([]) -> [N] = show([node()]), N; pick(L) -> case show(L) of [] -> pick([]); [H|T] -> N = select(H, T), N end. select(N, []) -> N; select(N, L) -> [H|T] = L, {_,Load} = N, {_,Load1} = H, case Load1 < Load of true -> N1 = H; false -> N1 = N end, select(N1, T).