Create a gist now

Instantly share code, notes, and snippets.

@cuihaoleo /balancer.sh Secret
Created Apr 30, 2017

Embed
What would you like to do?
#!/bin/bash
# Example:
#
# auto tun0
# iface tun0 inet static
# address 192.168.99.10
# netmask 255.255.255.255
# fakenet 192.168.99.0/24
# table 10000 10001
# rspec 192.168.99.10:10.99.0.10:10.99.1.10 \
# 192.168.99.20:10.99.0.20:10.99.1.20
# pre-up ip tuntap add mode tun tun0
# post-down ip tuntap del mode tun tun0
if [ -z ${IF_TABLE+x} ]; then
exit 0
fi
count=0
for table in ${IF_TABLE[@]}; do
ip route flush table $table
ip rule delete lookup $table || true
count=$((count+1))
done
for spec in ${IF_RSPEC[@]}; do
IFS=':' read -ra addr <<< $spec
dst=${addr[0]}
addr=("${addr[@]:1}")
ecmp_str=""
for table in ${IF_TABLE[@]}; do
gw=${addr[0]}
addr=("${addr[@]:1}")
if [ -n "$gw" ]; then
ip route add $dst via $gw src $IF_ADDRESS table $table
ecmp_str="$ecmp_str nexthop via $gw"
fi
done
ip route del $dst || true
ip route add $dst src $IF_ADDRESS $ecmp_str
done
iptables -t mangle -F
mark=0
for table in ${IF_TABLE[@]}; do
mark=$((mark+1))
iptables -t mangle -A OUTPUT -d $IF_FAKENET \
-m statistic --mode nth --every $count --packet $((mark-1)) \
-j MARK --set-mark $mark
ip rule delete fwmark $mark || true
ip rule add fwmark $mark lookup $table
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment