FreeBSD Balance

Материал из OpenWiki
Перейти к: навигация, поиск

FreeBSD: управление загрузкой 2-х каналов, отказоустройчивость и балансировка нагрузки

http://groups.google.ru/group/mailing.freebsd.ipfw/msg/9c440f25ee774686

Перевод: Сгибнев Михаил

Поздравьте меня - мне удалось реализовать схему подключения к 2-м каналам с возможностью управления пропускной способностью, отказоустойчивостью и объединением каналов. Для тех кто заинтересовался, привожу некоторые основы. Возможно, вы захотите модифицировать сценарии и изменить значения балансировки. Установка Все что нам потребуется: FreeBSD 5.4 - Stable ipfw, natd, natd2, ng_one2many, squid, jftpgw. 2 dsl подключения с Internet. 3 сетевые карты (по 1 на каждый dsl modem, 1 для lan) После длительного изучения материала, я пришел к выводу, что необходимо использовать ipfw prob, ipfw fwd и divert для разделения natd. В двух словах, natd с alias_address связвывается с соответствующим внешним IP.

Правила ipfw выглядят следующим образом:

 
#------------------------ 
route add default $ext_gw1 
<--snip--> 
ipfw add allow ip from any to any via $int_if 


ipfw add divert natd1 ip from any to $ext_ip1 in 
ipfw add divert natd2 ip from any to $ext_ip2 in 


# Simple version 
ipfw add skipto 8000 ip from $lan to any out 
ipfw add allow ip from any to $lan in 


ipfw add 8000 prob 0.5 skipto 8500 ip from any to any out 
ipfw add 8100 divert natd1 ip from any to any out 
ipfw add 8200 allow ip from $ext_ip1 to any out 
ipfw add 8500 divert natd2 ip from any to any out 
ipfw add 8600 fwd $ext_gw2 ip from $ext_ip2 to any out 


ipfw add deny ip from any to any out 
#------------------------

Эта схема не работает по двум причинам: Пакеты, попадающие под правило с fwd на ext_gw2 не поступали на нужный интерфейс, так как уже был прописан маршрут по умолчанию Сеансы TCP имеют определенный порядок следования пакетов и ответ ack поступает на тот интерфейс, с которого было инициировано соединение. К сожалению, keep-state создает динамическое правило используя только IP адрес, порт источника/назначения и интерфейс. Это не может нам помочь, так как я бы хотел создать правило, помнящее, какие пакеты попадают под skipto 8500, но keep-state (динамическое правило для этой сессии) посылает пакеты напрямую, видя только правило allow. Поскольку в таком случае пакеты не проходят через nat, мы их обратно уже никогда не получим.

Рабочим, хоть и не самым элегантным решением будет следущее:

Файл rc.conf должен содержать следущие строки:

hostname="fw.xx.yy.zz" 
# Configure the internal network 
ifconfig_vr0="inet 192.168.1.1 netmask 255.255.255.0" 
# Configure the external networks (connected to the internet) 
ifconfig_rl0="inet 192.168.8.70 netmask 255.255.255.0" 
ifconfig_rl0_alias0="inet 192.168.0.99 netmask 255.255.255.0" 
defaultrouter="192.168.8.1" 


# - Enabling the FreeBSD Firewall 
gateway_enable="YES" 
firewall_enable="YES" 
firewall_script="/etc/ipfw.rules" 
firewall_logging="YES" 


# Enabling natd for the 2 external interfaces 
natd_enable="YES" 
natd_flags="-f /etc/natd1.conf" 
# Remember to specify the natd2 port in /etc/services 
# To start this, the easiest way is to cp /etc/rc.d/natd 
/usr/local/etc/rc.d/natd2.sh and then edit it. 
natd2_enable="YES" 
natd2_flags="-f /etc/natd2.conf" 


#Enable the proxy server 
squid_enable="YES" 


# Sync server time from internet 
ntpd_enable="YES" 
ntpd_flags="-c /etc/ntp.conf" 


# Bandwidth monitoring with html graphs 
bandwidthd_enable="YES" 


# jftpgw ftp proxy for anonymous ftp proxy-cache 
jftpgw_enable="YES" 


# Load the script to hook the two external nic's together 
# Add the actual script file to /usr/local/etc/rc.d/netmon1.sh 
netmon1_enable="YES"

Я обнаружил, что команда fwd не отрабатывала правильно, пакеты не выходили с нужного интерфейса. Я решил передавать их так как надо, хотят они того или нет (довольно грубо, как вы увидите). Используя ng_one2many на первом внешнем интерфейсе и сконфигурив его на "перелавать все", я получил, что все пакеты, исходящие с первого интерфейса, отправляются и со второго. В результате родился следующий сценарий: (Да я знаю, что это может быть сделано намного лучше - пока это работает!!!)

#---------------------------- 
#!/bin/sh 
# Load the kernel modules 
kldload ng_ether 
kldload ng_one2many 


ifconfig rl0 down 
ifconfig rl1 down 
# Plumb nodes together 
ngctl mkpeer rl0: one2many upper one 
ngctl connect rl0: rl0:upper lower many0 
ngctl connect rl1: rl0:upper lower many1 


# Allow rl1 to xmit / recv rl0 frames 
ifconfig rl1 promisc 
ngctl msg rl1: setautosrc 0 
# Configure to transmit to all interfaces 
ngctl msg rl0:upper setconfig "{xmitAlg=2 failAlg=1 enabledLinks =[ 1 1 ] }" 


echo "Now up the interfaces again" 
ifconfig rl0 up 
ifconfig rl1 up 
ifconfig rl0 inet 192.168.8.70 netmask 255.255.255.0 
ifconfig rl0 inet 192.168.0.99 netmask 255.255.255.0 alias 
Make sure the default route is correct. 
route delete default 
route add default 192.168.0.1 
echo "Done" 
#----------------------------

Темные электрические силы не давали работать, пока в качестве маршрута по умолчанию был указан 192.168.8.1 (через интерфейс, к которому непосредственно подключен $ext_if1). Как только шлюзом был указан $ext_gw2 - все заработало.

Правила IPFW:

#!/bin/sh 

# Flush out the list before we begin. 
ipfw -q -f flush 


# Set rules command prefix 
cmd="ipfw -q add" 
bwm="ipfw -q pipe" 
skip="skipto 8000" 
ext_if1="rl0"         # public interface name of NIC 
ext_if2="rl0" 
lan="192.168.1.0/24" 
int_if="vr0"    # private interface name of NIC 
ext_ip1="192.168.8.70" 
ext_ip2="192.168.0.99" 
ext_gw1="192.168.8.1" 
ext_gw2="192.168.0.1" 


# Setup the different Sets to be used for different connection options 
ipfw -q set disable 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 
21 22 23 24 25 26 27 28 29 30 31 
# Initially enable set 1 and 2 and 12 assuming we have 2 WAN links up 
and working 
ipfw -q set enable 1 2 12 


# Specify which ip addresses get what bandwidth 
# Can also tell this dhcp server to give certain addresses to selected mac 
# addresses in file /usr/local/etc/dhcpd.conf 
u512k=""      # Users given 512kb/s link 
u256k="192.168.1.0/24{2-254}"         # Users given 256kb/s link 
u128k=""         # Users given 128kb/s link 
u64k=""         # Users given 64kb/s link 
# squid and jftpgw have to be configured seperately to provide the same 
# bandwidth management as what is configured here. See their config/man 
pages. 


# Check and drop packets that are appearing to come from 
# the destination LAN i.e. a spoofed source ip address 
$cmd deny ip from any to any not antispoof in 


# No restrictions on Loopback Interface 
# Protect spoofing to localhost 
$cmd allow ip from any to any via lo0 
$cmd deny ip from any to 127.0.0.0/8 
$cmd deny ip from 127.0.0.0/8 to any 


# check if packet is inbound and nat address if it is 
$cmd 1000 divert natd1 ip from any to $ext_ip1 in 
$cmd 1000 divert natd2 ip from any to $ext_ip2 in 


# Divert incoming http and ftp traffic to the proxy (squid and jftpgw) 
$cmd fwd 192.168.1.1,3128 tcp from $lan to any 80 in via $int_if 
$cmd fwd 192.168.1.1,2370 tcp from $lan to any 21 via $int_if 


# Allow the rest of the LAN traffic in and out 
$cmd allow ip from any to any via $int_if 



# Setup up pipes for each of the user groups 


# Users with 512Kb / 256Kb access (in / out) 
$cmd pipe 10 ip from any to $u512k in via $ext_if1 
$cmd pipe 11 ip from $u512k to any out via $ext_if1 
$bwm 10 config mask dst-ip 0x000000ff bw 512Kbit/s queue 4KBytes 
$bwm 11 config mask src-ip 0x000000ff bw 256Kbit/s queue 3KBytes 


# Users with 256Kb / 128Kb access 
$cmd pipe 20 ip from any to $u256k in via $ext_if1 
$cmd pipe 21 ip from $u256k to any out via $ext_if1 
$bwm 20 config mask dst-ip 0x000000ff bw 256Kbit/s queue 4KBytes 
$bwm 21 config mask src-ip 0x000000ff bw 128Kbit/s queue 3KBytes 


# Users with 128Kb / 64Kb access 
$cmd pipe 30 ip from any to $u128k in via $ext_if1 
$cmd pipe 31 ip from $u128k to any out via $ext_if1 
$bwm 30 config mask dst-ip 0x000000ff bw 128Kbit/s queue 4KBytes 
$bwm 31 config mask src-ip 0x000000ff bw 64Kbit/s queue 3KBytes 


# Users with 64Kb / 56Kb access 
$cmd pipe 40 ip from any to $u64k in via $ext_if1 
$cmd pipe 41 ip from $u64k to any out via $ext_if1 
$bwm 40 config mask dst-ip 0x000000ff bw 64Kbit/s queue 3KBytes 
$bwm 41 config mask src-ip 0x000000ff bw 56Kbit/s queue 2KBytes 



# Interface facing Public Internet (Outbound Section) 


# Allow out access to my ISP's Domain name server. 
# Get the IP addresses from /etc/resolv.conf file 
#$cmd $skip UDP from any to { 196.7.0.138 or 196.28.86.2 or 196.28.86.3 
or 196.25.1.1 } 53 out 
$cmd $skip UDP from any to any 53 out 


# Allow this box out access to my ISP's DHCP server (or adsl router) 
$cmd $skip udp from me to any 67 out 


# Allow skype connections out 
# Allow ntp time server out 
$cmd $skip UDP from any to any 80,443,123,1024-65535 out 
$cmd $skip UDP from any 80,443,1024-65535 to any out 
$cmd $skip tcp from any 1024-65535 to any 1024-65535 out 


# Allow out non-secure standard www function - via proxy 
$cmd $skip tcp from me to any 80 


# Allow out secure www function https over TLS SSL 
# Allow out send & get email function (GMail uses ports 587, 995) 
# Allow out MSN messenger 
# Allow out Time, nntp news (i.e. news groups), 
# SSH (secure FTP, Telnet, and SCP), whois 
$cmd $skip tcp from any to any 443,25,110,587,995,1863,37,119,22,43 out 


# Allow out regular http and ftp access (for if proxy and fwd cmd's 
above are off) 
$cmd $skip tcp from $lan 1024-65535 to any 20,21,80 out 


# Allow out ping 
$cmd $skip icmp from $lan to any out icmptypes 8 
$cmd allow icmp from me to 192.168.0.0/16 out icmptypes 8 
$cmd allow icmp from $ext_ip1,$ext_ip2 to any out icmptypes 8 


# Allow www and ftp proxy out 
$cmd $skip tcp from me to any 20,21,80 out uid squid 


# Allow out FreeBSD (make install & CVSUP) functions 
# Give user root "GOD" privileges. 
$cmd allow ip from me to any out uid root 


# Deny the rest out 
$cmd deny log ip from any to any out 



# Interface facing Public Internet (Inbound Section) 
# Interrogate packets originating from the public Internet 
# destine for this gateway server or the private network. 


# Deny all inbound traffic from non-routable reserved address spaces 
#$cmd 300 deny all from 192.168.0.0/16  to any in via $ext_if1  #RFC 
1918 private IP 
$cmd deny all from 
172.16.0.0/12,10.0.0.0/8,0.0.0.0/8,169.254.0.0/16,192.0.2.0/24,204.152.64.0/23,224.0.0.0/3 
to any in 
#RFC 1918 private IP #DHCP auto-config #reserved for docs #Sun cluster 
#Class D & E multicast 


# Deny ident 
# Deny all Netbios service. 137=name, 138=datagram, 139=session 
# Netbios is MS/Windows sharing services. 
# Block MS/Windows hosts2 name server requests 81 
$cmd deny all from any to any 113,137,138,139,81 in 


# Allow traffic in from ISP's DHCP server. This rule must contain 
# the IP address of your ISP's DHCP server as it's the only 
# authorized source to send this packet type. 
$cmd allow udp from 192.168.8.1,192.168.0.1 to any 68,5678 in 


# Allow dns lookups back in 
$cmd allow udp from any 53,67 to $lan in 
$cmd allow udp from any 53,67 to me in 


# Allow skype connections in 
$cmd allow udp from any 80,123,443,1024-655353 to $lan in 
$cmd allow udp from any to $lan 80,443,1024-655353 in 
$cmd deny log udp from any to any in # Deny the rest 
$cmd allow tcp from any 1024-65535 to $lan 1024-65535 in 


# Allow in SecureFTP and SSH from public Internet 
$cmd allow tcp from { 192.168.0.0/24 or $lan or 192.168.8.0/24 } to me 
22 in  #setup limit src-addr 3 
$cmd allow tcp from any to me 22 in setup limit src-addr 1 


# Allow in standard www function because I have Apache server - or is 
there an internal webserver? 
# Allow Webmin connections from close-by 
$cmd allow tcp from { 192.168.8.0/24 or 192.168.0.0/24 } to me 80,10000 in 
$cmd allow tcp from any to $lan 80,10000 in 


# Allow outgoing web traffic (via proxy) back in 
$cmd allow tcp from any 20,21,80 to me 1024-65535 in 


# Deny the rest to me 
$cmd deny log tcp from any to me in 


# Allow out regular ftp, http access if proxy is off 
$cmd allow tcp from any 20,21,80 to $lan 1024-65535 in 


# Allow in secure www function https over TLS SSL 
# Allow in send & get email function (GMail uses ports 587, 995) 
# Allow in MSN messenger 
# Allow in Time, nntp news (i.e. news groups), 
# SSH (secure FTP, Telnet, and SCP), whois 
$cmd allow tcp from any 443,25,110,587,995,1863,37,119,22,43 to any in 


#Allow in ICMP (ping) from public networks close by only. 
$cmd allow icmp from 192.168.0.0/16 to me in icmptypes 0,3,11 
$cmd allow icmp from any to $lan in icmptypes 0,3,11 
#  Used for testing network connections 
$cmd allow icmp from 196.7.0.138,196.25.1.1,196.4.160.7 to me in 
icmptypes 0,3,11 


#Deny the rest 
$cmd deny icmp from any to any in 


# Reject & Log all unauthorized incoming connections from the public 
Internet (/var/log/security) 
$cmd deny log all from any to any in 


# This is skipto location for outbound stateful rules 
$cmd 8000 skipto 9000 tcp from any to any out setup 
$cmd 8010 skipto 9000 udp from any to any out 
$cmd 8020 skipto 9000 icmp from any to any out 
$cmd 8100 tee natd1 ip from any to any out 
$cmd 8150 check-state 
$cmd 8200 divert natd2 ip from any to any out 
$cmd 8250 check-state 
$cmd 8400 deny ip from any to any out 
$cmd 9000 set 12 prob 0.5 skipto 9500 ip from any to any out 
$cmd 9100 set 1 divert natd1 ip from any to any out 
$cmd 9200 set 1 allow ip from any to any out keep-state 
$cmd 9500 set 2 divert natd2 ip from any to any out 
$cmd 9600 set 2 allow ip from any to any out keep-state 


# deny and log all packets that fell through to see what they are 
$cmd 9999 deny log all from any to any 

Работа всей конструкции достигается за счет отправки пакета по обоим интерфейсам, что приводит к загрузке каналов лишним трафиком.

Теперь нам необходимо обеспечить отказоустойчивость. Мной опять был написан представленный ниже сценарий и добавлен в crontab на выполнение раз 2 минуты.

#----------------------------------------- 
#!/bin/sh 
target="196.7.0.138" 
ext_gw1="192.168.8.1" 
ext_gw2="192.168.0.1" 


# Setup route to ping through 
route -q add -host $target $ext_gw1 
# Test link one through ext_gw1 to see if any packets get returned 
ping1=$( ping -q -c 3 -f -s 8 -o -t 2 196.7.0.138 | grep "packet loss" | 
cut -c24-24 ) 
# Test link two through ext_gw2 to see if any packets get returned 
route -q delete $target 
route -q add -host $target $ext_gw2 
ping2=$( ping -q -c 3 -f -s 8 -o -t 2 196.7.0.138 | grep "packet loss" | 
cut -c24-24 ) 
# Remove route 
route -q delete $target 


# Configure the ipfw sets as per network route availability 
if [ "$ping1" != "0" ]; then 
    if [ "$ping2" = "1" ]; then 
    ipfw set enable 1 2 12 
    else 
    ipfw set enable 1 
    ipfw set disable 2 12 
    fi 
else 
    if [ "$ping2" != "0" ]; then 
        ipfw set disable 1 12 
    ipfw set enable 2 
    else 
    # echo "enabling everything to wait for network recovery" 
    ipfw set enable 1 2 12 
    fi 
fi 
#--------------------------------------

Из всего этого можно сделать систему управления пропускной способностью, если добавить правила к ipfw, которые определят вероятность 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8 с каждым правилом, связанным с разными наборами правил ipfw. Тогда необходимо анализировать ответы утилиты ping (необходимо среднее значение нескольких пакетов) для определения среднего времени доступа по разным маршрутам и установка соответствующего набора правил ipfw с соответствующим значением ipfw prob. В теории все должно работать.

Regards Graham