Skip to content

Instantly share code, notes, and snippets.

@leandrosilva
Created May 8, 2010 22:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save leandrosilva/394820 to your computer and use it in GitHub Desktop.
Save leandrosilva/394820 to your computer and use it in GitHub Desktop.
Load balancer module for Erlang
%%
%% Load balancer
%%
%% Author: Krzysztof KliÅ› <krzysztof.klis@gmail.com>
%%
%% 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 <http://www.gnu.org/licenses/>.
%%
-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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment