Gateway switching using Erlang for ISP active passive load-balancing

From Notes_Wiki

Home > Erlang > Useful erlang scripts > Gateway switching using Erlang for ISP active passive load-balancing

Use gateway.erl with following contents:

-module(gateway).
-compile(export_all).

start() ->
  main(["4.2.2.2", "192.168.4.1", "192.168.5.1"]),
  receive after infinity -> stop end.

main(Args) ->
        io:format("Script called with ~p arguments ~n", [Args]),
	if 
		length(Args) < 3 ->
			io:format("Required IP, Gateway1, Gateway2~n");
		true ->
			[Ping_ip, Gateway1, Gateway2] = Args,
			shift_to_gateway2(Ping_ip, Gateway1, Gateway2)
	end.

is_ip_alive(IP1) ->
	Cmd1=lists:flatten(io_lib:format("ping -c 10 -q ~s", [IP1])),
	Ping_lines1=string:tokens(os:cmd(Cmd1), "\n"),
	Stats_line1 = lists:nth(3, Ping_lines1),
	Received1 = lists:nth(2, string:tokens(Stats_line1, ",")),
	Received_count1=list_to_integer(hd(string:tokens(Received1, " "))),
	%%io:format("Count is ~p~n", [Received_count1]),
       	Received_count1.	



shift_to_gateway2(Ping_ip, Gateway1, Gateway2) ->
	receive
        after 60000 -> ok
        end,
	Ping_count1=is_ip_alive(Ping_ip),
	if
		Ping_count1 > 0 ->
			io:format("~p ~p Everything fine with Gateway1, continuing ~n", [date(), time()]),
			shift_to_gateway2(Ping_ip, Gateway1, Gateway2);
		true ->
			os:cmd("ip route del default"),
			Cmd1 = lists:flatten(io_lib:format("ip route add default via ~s", [Gateway2])),
		        os:cmd(Cmd1),
			shift_to_gateway1(Ping_ip, Gateway1, Gateway2)
	end.


shift_to_gateway1(Ping_ip, Gateway1, Gateway2) ->
	receive
        after 60000 -> ok
        end,
	Ping_count1=is_ip_alive(Ping_ip),
	if
		Ping_count1 > 0 ->
			io:format("~p ~p Everything fine with Gateway2, continuing ~n", [date(), time()]),
			shift_to_gateway1(Ping_ip, Gateway1, Gateway2);
		true ->
			os:cmd("ip route del default"),
			Cmd1 = lists:flatten(io_lib:format("ip route add default via ~s", [Gateway1])),
		        os:cmd(Cmd1),
			shift_to_gateway2(Ping_ip, Gateway1, Gateway2)
	end.


Then call it externally on machine start up using:

 erl -noshell -s gateway start -s init stop </dev/null  >> /root/gateway.out 2>&1 &

This way as per hardcoded values in start() function the program with try to ping IP "4.2.2.2". If the ping fails it will keep switching the gateway between 192.168.4.1 and 192.168.5.1.



Home > Erlang > Useful erlang scripts > Gateway switching using Erlang for ISP active passive load-balancing