Openwrt настройка 2 провайдера
В этой статье я расскажу о том как настроить сеть в OpenWRT. В частности расскажу о том как сделать несколько SSID на одной радиокарте, настроить WPA2-Enterprise, поднять VLAN и как настроить программный свитча(swconfig).
Все настройки будем проводить через консоль так как она не ограничена в возможностях в отличии от веб интерфейса. Для настроек системы в OpenWRT используется подсистема UCI(Unified Configuration Interface), которая позволяет централизовано настраивать всевозможные сервисы начиная с сервиса монтирования файловых систем и заканчивая сервисом QoS. Все настройки UCI находятся в директории "/etc/config/" и имеют одинаковый синтаксис. Для управления системой UCI используется программа uci. С помощью неё можно редактировать конфигурационные файлы, просматривать текущие настройки и прочее. uci очень удобно использовать для конфигурирования системы из скриптов. Так-же есть возможность писать расширения для uci. Синтаксис конфигурационных файлов такой:
config 'example' 'test' — начало секции, example — тип по которому uci поймет как трактовать опции в этой секции, test — идентификатор секции. option или list определяет тип настроек, list — составные настройки(например список интерфейс для прослушивания apache'ем). string, boolean, collection — названия переменных.
Настройка сетевых интерфейсов
Конфигурационный файл — /etc/config/network.
В простейшем случае настройка сети выглядит так:
Где lan это роль данного интерфейса. Нужна она для того что-бы можно было абстрагироваться от названия интерфейсов. Например можно в фаерволе указать что разрешить весь входящий трафик c lan.
Пример добавления статического маршрута:
Отмечу что интерфейс обязательно надо указывать.
Пример настройки влана и добавление его в bridge:
Создаст интерфейс «br-guest» и включит в него интерфейс eth1.123(123 vlan-id на интерфейсе eth1). Ниже будет пример как добавить в этот бридж беспроводной интерфейс.
Так как чипсеты используемые в роутерах обычно имеют 1-2 ethernet порта, а хочется побольше, то используется отдельных контроллер для ethernet. Он подключается одним портом в главный чипсет, а остальными наружу. Непосредственно в сетевой системе такой программный коммутатор никак не представлен. Коммутатор можно настроить через утилиту swconfig, либо через uci. Предположим у нас есть один ethernet порт eth0 подключенный к 5-му порту управляемого коммутатора:
Здесь eth0 — название интерфейса куда подключен коммутатор. В первой секции включаем коммутатор и включаем поддержку теггированного(трафика с вланом) трафика. Каждая секция switch_vlan отвечает за определенный VLAN указанный в опции vlan. Этот тег будет использоваться для добавления метки для портов указанных в секции ports. Буква t у порта обозначает что трафик в этот порт должен быть передан теггированным(с меткой), в остальные перечисленные порты он попадет без метки. Запись '0 1 2 5t' нужно читать так: передай нетегированный трафик с портов 0, 1, 2 в порт 5 с меткой 0. Так как VLAN с меткой 0 это тоже самое что трафик без метки, то на нашем порту eth0 мы получим трафик с портов 0, 1, 2 без всяких вланов. В следующей секции написано: ports='3 5t', vlan=1. Это значит что нетегированный трафик с порта 3 придет на eth0 с vlan-id=1(не рекомендую использовать vlan-id=1). В последней секции написано vlan=124, port=«6t 5t» — это значит что трафик пришедший на порт6 с тегом 124 придет на eth0 с тегом 124.
В network можно настроить подключения типа PPTP, PPPoE и даже 6to4.
Настройка wi-fi:
Конфигурационный файл находиться тут — /etc/config/wireless.
Настройка радио интерфейсов разделена на две части: настройки уровня phy(физика) и настройка интерфейса. Минимальные настройки выглядят так:
В первой секции мы указали что тип чипсета/драйвера — mac80211(определяется при загрузке), используемый канал — 6. Так-же можно указать используемые стандарты, мощность передатчика, используемые антенны и прочее. Во второй секции уже описываем сам интерфейс. Интерфейсов может быть несколько, например с разными SSID. В опции device необходимо указать идентификатор секции с описание устройства, в данном случае radio0. network=guest значит что нужно прикрепить это устройство к интерфейсу guest использующемся в network. Так как у нас(смотри выше) в описание сети написано что interface=guest это бридж, то этот беспроводной интерфейс добавить в бридж br-guest.
Пример настройки multi-ssid с шифрованием wpa2-enterprise+ccmp:
В статье описана настройка OpenWRT для подключения резервного канала на случай падения основного. В качестве примера взята реальная конфигурация одной организации, где в качестве резерва используется интернет-подключение через маршрутизатор соседней (дружественной) организации. Адрес IP провайдера заменён на адрес из пула “адресов для документирования”
MWAN3 configuration
A mwan3 configuration consists of four section elements, namely:
OpenWrt 12.09 и версии старше
Таким способом Вы можете вручную установить пакет mwan3 а также для версий старших от 12.09. (Смотрите ниже)
OpenWrt 14.07 and later
Метод использующий веб интерфейс LuCi
In the “Download and install package:” box, enter “luci-app-mwan3” and click OK to download and install the luci-app-mwan3 package and all related packages, including mwan3 itself and all dependencies
SSH method
Test external DNS/mail/etc. servers for access from each WAN interface
Option 3: Create user rules for traffic destined to “private” DNS servers to only exit the correct interface.
Установка пакетов
Для удобства управления устанавливаем web-интерфейс LuCI:
Затем устанавливаем пакет luci-app-miltiwan (модуль управления multiwan для LuCI), при установке которого автоматически ставится также и нужный multiwan.
Обновление
Обновление производится только установкой пакетов со старшими версиями.
The configuration file /etc/config/mwan3 will be the new, default version. The previous mwan3 file will be renamed as “mwan3-opkg.backup” but otherwise left intact in /etc/config as well
Manually update the new version of /etc/config/mwan3 to ensure interface names are correct and that previously configured interface, member, policy and rule settings are re-entered. Note that some keywords have been dropped over time (e.g. “option reroute”) so follow the lead of how the default mwan3 file is configured.
Check its status in LuCI or from the command line (see below) to confirm all expected interfaces are up and testing OK
Установка
Rule configuration
A rule describes what traffic to match and what policy to assign for that traffic. These are the available options:
Name | Type | Required | Default | Description |
---|---|---|---|---|
use_policy | string | yes | (none) | Use this policy for traffic that matches or set to default to use the default routing table to lookup |
src_ip | ip address | no | any | Match traffic from the specified source ip address |
src_port | port or range | no | any | Match traffic from the specified source port or port range, if relevant proto is specified |
proto | protocol | no | all | Match traffic using the given protocol. Can be one of tcp , udp , icmp or all or it can be a numeric value, representing one of these protocols or a different one |
dest_ip | ip address | no | any | Match traffic directed to the specified destination ip address |
dest_port | port or range | no | any | Match traffic directed at the given destination port or port range, if relevant proto is specified |
ipset | string | no | (none) | Match traffic directed at the given destination ip address to an ipset set |
sticky | boolean | no | 0 | Allow traffic from the same source ip address within the timeout limit to use same wan interface as prior session |
timeout | number | no | 600 | Stickiness timeout value in seconds |
There are a number of sample rules defined to show how they work. Edit the rules as desired and delete all the rest of the default rules.
A typical rule section looks like this:
Stickiness and ipset
With sticky set to 1, this rule has now sticky enabled. When a packet for a new session matches this rule, its source ip address and interface mark are stored in an ipmark set with a timeout of 300 seconds (default 600). When packet for a second new session from the same lan host within the timeout period matches this rule, it will use the same wan interface as the first packet and the timeout counter is reset back to 300 again.
Stickiness is on a per rule basis. With this example, all traffic from lan hosts will use the same wan interface for all youtube hosts, even if the source or destination ip address differs.
The option ipset matches only destination ip addresses. This example will only work if your lan clients use the dnsmasq server as their one and only dns server. Mwan3 will create the ipset set for you if it does not exist already. For this to work you need to configure a rule in your /etc/dnsmasq.conf file:
Order is important. Rules are evaluated in top-to-bottom order, with the first matching rule applying. The rule name is just descriptive and has no operational impact. If no match is found, routing lookup is done via the default routing table.
версии OpenWrt
Member configuration
Each member represents an interface with a metric and a weight value. Members are referenced in policies to define a pool of interfaces with corresponding metric and load-balancing weight. Members can't be used for rules directly. The default settings are described below:
Name | Type | Required | Default | Description |
---|---|---|---|---|
interface | string | yes | (none) | Member applies to this interface (use the same interface name as used in the mwan3 interface section, above) |
metric | number | no | 1 | Members within one policy with a lower metric have precedence over higher metric members |
weight | number | no | 1 | Members with same metric will distribute load based on this weight value |
A typical member section looks like this:
Настройка маршрутизатора
В качестве маршрутизатора был выбран NetGear WNDR3800, при выборе решающим было: большая оперативная память (128 Мб), большая ёмкость флешки (64 Мб), поддерживается как в DD-WRT, так и в OpenWRT.
Поскольку фирменная прошивка не позволяет использовать двух аплинков, решено было попробовать OpenWRT с пакетом multiwan, а в случае неудачи - dd-wrt с собственным скриптом.
Конфликты пакетов
Verify outbound traffic on each WAN interface
Проверка первого интернет (first WAN) соединения
Убедитесь что пинг проходит по этому интерфейсу (“1 packets transmitted, 1 packets received, 0% packet loss” should be displayed)
Проверка wan2 соединения
Ensure the single ping is successful on this interface (“1 packets transmitted, 1 packets received, 0% packet loss” should be displayed)
Проверка всех остальных WAN соединений
Configuration
Правила для исходящего трафика
Если несколько правил перекрываются, действует правило, расположенное последним в файле конфигурации. ( not clear enough.)
Имя параметра | Значение по умолчанию | Варианты значения | Описание |
---|---|---|---|
src | all | all// | Адрес источника: all (любой), адрес IP либо имя хоста |
dst | all | all// | Адрес получателя: all (любой), адрес IP либо имя хоста |
port_type | dports | dports/source-ports | Тип порта: порт источника или порт получателя |
ports | all | all/ | Номера портов: все, один либо диапазон |
proto | all | all/tcp/udp/icmp/ | Протокол: все, мнемоническое имя из /etc/protocols либо номер |
wanrule | balancer/fastbalancer/ | Правило распределения WAN : балансировка iproute2 или iptables, либо имя интерфейса | |
failover_to | balancer/fastbalancer/ | Резервный линк при отказе этого линка |
Как mwan3 производит баллансировку трафика
Такая балансировка нагрузки поможет ускорить несколько отдельных загрузок или трафик, генерируемый группой исходных компьютеров, обращающихся к разным сайтам, но не ускорит одну загрузку с одного компьютера (если загрузка не распределена по нескольким IP -потокам, например, с использованием менеджер загрузок)
Mwan3 Роутинг
The following steps are taken to route a packet with mwan3 (version 2.0 or higher):
Every incoming packet (this includes router originated traffic) is handled by the iptables mwan3_hook. This hook takes 5 steps:
Check if the packet arrives on a wan interface. If originated from a local connected ip network, then mark packet with iface_id 255 (default). If the packet is from another (non-local) network and arrives on wan interface, then mark it with iface_id. If successful marked, goto step 5.
Check if packet destined for a known ip network (has a route for it other than default). If so then mark packet with iface_id 255 (default) and goto step 5.
Check if packet source address is that of a wan interface. If so use that wan interface for routing regardless of user defined rules and mark packet with iface_id of corresponding wan.
Ip rules 1001 till 1250 are for wan interface 1 till 250 respectively. This rule says: If packet is incoming from wan interface use main routing table, regardless of mark.
Ip rules 2001 till 2250 are for wan interface 1 till 250 respectively. This rule says: If packet is marked with iface_id 74, use the corresponding wan interface routing table.
Ip rule 2253 is a blackhole rule. This rule states: If packet is marked with iface_id 253 (blackhole), silently drop packet.
Ip rule 2254 is a blackhole/unreachable rule. This rule states: If packet is marked with iface_id 254 (unreachable), drop packet and return icmp unreachable.
Next up are the routing tables. These are really simple. There is just the standard main routing table and one routing table containing one gateway for each wan interface. Route table 1 for the first wan, route table 2 for the second and so on. Hopes this make troubleshooting easier.
Настройка
Подключение к Основному аплинку
В UCI нужно изменить файл /etc/config/network:
и применить изменение:
Создаём VLAN
Для удобства коммутации назначим в VLAN2 порт с подписью “Ethernet 1” (на лицевой стороне индикатор “1”): он расположен рядом с портом, подписанным “Internet” (соответствует интерфейсу WAN ). В конфигурации управляемого коммутатора, который имеется в маршрутизаторе, порту “1” соответствует “Port 3” (см. NetGear WNDR3800).
Таким образом, нужно назначить порт 3 коммутатора в VLAN2.
После внесения изменений в /etc/config/network нужно не забыть применить новую конфигурацию сети:
Настраиваем multiwan
Сопоставление интерфейсов
Во-первых, нужно сопоставить физическому интерфейсу виртуальный, c которым будет работать multiwan.
В UCI для того же нужно в файле /etc/config/network добавить строки:
Настройка межсетевого экрана
Во-вторых, нужно задать параметры файрвола для этого нового интерфейса: в LuCI на странице Network → Interfaces → WWAN → Firewall settings нужно выбрать зону wan.
Настройка параметров multiwan
Во-третьих, нужно задать параметры multiwan для этого нового интерфейса. Но, оказывается, в конфигурации multiwan уже есть два интерфейса: WAN и WAN2. Придётся удалить ненужный WAN2 (он не ассоциирован ни с одним системным интерфейсом) и создать WWAN .
Failover Traffic Destination, который должен указывать на другой интерфейс, участвующий в multiwan: у WAN нужно вписать wwan, а у WWAN - wan;
Затем назначим политику multiwan:
Основной аплинк будет использоваться для всего трафика, резервный только в случае его падения.
Применяем изменения: Save & Apply, ждём завершения и проверяем работу.
При использовании UCI нужно изменить файл /etc/config/multiwan следующим образом:
После изменения файла /etc/config/multiwan нужно перезапустить службу multiwan:
Настраиваем dnsmask
В UCI: в файле /etc/config/dhcp нужно в секцию config dnsmasq добавить строки list server … , пример:
После редактирования файла /etc/config/dhcp нужно применить изменения:
Теперь компьютеры в локальной сети могут выходить в интернет без проблем.
- Last modified: 2019/03/22 11:00
- by vgaetera
Self-registration in the wiki has been disabled.
If you want to contribute to the OpenWrt wiki, please post HERE in the forum or ask on IRC for access.
Except where otherwise noted, content on this wiki is licensed under the following license:
CC Attribution-Share Alike 4.0 International
Конфигурационный файл /etc/config/multiwan является частью пакета multiwan. Этот пакет представляет собой скрипт, который позволяет сделать конфигурацию с несколькими провайдерами простой и легко управляемой. Пакет multiwan содержит легко настраиваемый набор правил распределения нагрузки и отказоустойчивости.
Условия и определения
Основной аплинк - подключение по кабелю ethernet к провайдеру с назначенным статическим адресом IP .
Резервный аплинк - подключение по кабелю ethernet к маршрутизатору соседней организации, адрес выделяется по DHCP из интранетовской сети.
Основное условие: используемое в сетях обоих организаций адресное пространство не должно пересекаться, то есть подсеть 192.168.1.0/24 не может использоваться одновременно в обоих организациях. В нашем примере резервный аплинк использует адресное пространство 192.168.20.0/25, а маршрутизатор использует подсеть 192.168.1.0/24, поэтому изменять адрес и маску для интерфейса LAN нужды нет.
Mwan3 архитектура
Mwan3 запускается событиями hotplug. Когда появляется интерфейс, он создает собственную таблицу маршрутизации и правила iptables. Новая таблица маршрутизации создается для каждого интерфейса. Затем он устанавливает правила iptables и использует iptables MARK для маркировки определенного трафика. На основании этих правил ядро определяет, какую таблицу маршрутизации использовать. Когда интерфейс выходит из строя, mwan3 удаляет все правила и маршруты к этому интерфейсу.
Как только все маршруты и правила установлены, mwan3 завершает работу. Ядро берет на себя все решения по маршрутизации. Если происходит событие горячей замены нового интерфейса, mwan3 снова запустится, чтобы настроить маршрут и таблицы по мере необходимости.
Перезагрузите роутер через веб интерфес LuCI или другим доступным методом если это необходимо
To ensure the new menu item for mwan3 appears, restart the web server hosting the LuCI interface (or just reboot the router).
В меню веб интерфейса LuCi должна появится новая запись “Network > Load Balancing” .
3. Test
Try a torrent with lots of seeders. If multiwan is working properly you should see a download rate greater than your fastest WAN connection.
Установка OpenWRT
Установка тривиальна: качаем прошивку (взята прошивка из trunk, поскольку стабильная прошивка Backfire, как пишет народ, “из коробки” не поддерживает адаптеры wifi), затем заливаем её в маршрутизатор стандартной процедурой Firmware upgrade.
После ожидания и ручного перезапуска маршрутизатора подключаемся к нему по telnet и задаём пароль, после чего telnet-демон будет автоматически выключен и включится sshd:
Второй WAN интерфейс (wan2)
Prepare and the check the default routing table for the wan interfaces
Step 1: Configure a different metric for each WAN interface
IMPORTANT: This is an important step and is compulsory. Time and time again fail to configure this and have a none working setup
Note: PPPoE connections only show the “Use gateway metric” option if “Use default gateway” option is enabled.
wan setting
wan is the default wan interface in this example, and so will get a metric of 10.
wan2 setting
wan2 is the second wan interface in this example, and so will get the a metric of 20.
Verify the routing table
If configured correctly, you should have a default gateway (the lines with a target address of 0.0.0.0/0) with a unique metric set for each WAN interface. For example:
Troubleshooting
Interfaces are missing a metric value
There was a report of some wireless interfaces missing a metric value and a gateway. The mwan3 syslog message error was “user.warn mwan3: Could not find gateway for interface wan1 (wlan0)”
With Command Line Interface (CLI)
Policy configuration
If there is more than one member assigned to a policy, members within the policy with a lower metric have precedence over higher metric members. Members with the same metric will load-balance. Load-balancing members (with same metric) will distribute load based on assigned weights values.
A typical policy section looks like this:
If a policy is not referenced by a specific traffic rule, the policy will not do anything, so it is fine to leave unused policies in place in case they are desired in the future.
Ручная загрузка пакетов
This step is only required for OpenWrt 12.09. In OpenWrt 14.07 “Barrier Breaker” and later, the mwan3 packages are in the standard package repositories and no manual download is required.
Adze and Arfett keep the OpenWrt package repositories up to date and you are more likely to download the recommended latest “stable” version from there.
Рекомендованый метод загрузки заключается в подключении к роутеру посредством telnet или SSH и загрузки пакетов в директорию /tmp.
или для версии 2.0
Зависимости пакетов
The following packages are required, but they should be installed automatically if missing when mwan3 is installed so there is no need to manually install them beforehand
libc, ip, iptables, iptables-mod-conntrack-extra, iptables-mod-ipopt, kmod-ipt-conntrack-extra, kmod-ipt-ipopt
Посредством графического интерфейса LuCI
В LuCI выполните шаги:
В результате будет установлен пакет multiwan и пакет управления им через LuCI luci-app-multiwan. После установки при очередном обновлении веб-страницы, Вы сможете настраивать пакет multiwan на странице Network → Multi-WAN
Посредством командной строки (CLI)
Installation
1. Create VLAN for WAN2
With LuCI interface
System → Software → Scroll down to Available packages → Click the “Install” link for the luci-app-multiwan package.
For Chaos Calmer snapshots instead:
System → Software → Scroll down to Available packages → Click the “Install” link for the luci-app-mwan3 package.
You should now find the multiwan configuration page under Network → Multi-WAN
Simple Multiwan Setup
Quick Multiwan setup guide by AndyBallon
1. Установка Backfire 10.03
tftp note: don't forget to login via telnet and change root passwd for ssh to work
2. Create extra Vlan for Wan2
I do this via /etc/config/newtork.
Note: I removed port “0” from eth0_0 and gave it to eth0_2.
You can configure wan and wan2 proto as dhcp to strt and then use the web interface to configure the pppoe or static ip later. Use the same DNS servers I'm using if you're having DNS problems. Some ISPs only allow DNS connections from their IP blocks.
3. Install prerequisite software
ip, iptables, iptables-utils, iptables-mod-conntrack, iptables-mod-conntrack-extra, iptables-mod-ipopt and kmod-ipt-ipopt this is how I do it:
4. Install multiwan and it's web control package (luci-app)
Reboot to refresh the web ui. I always need to do this otherwise the link does not show up in networking.
5. Configure Wans && configure multiwan
Wans: Network > Interfaces > Wan/WAN2 note: when asked which firewall zone to add wan2 choose wan so it has the same firewall rules for wan connections. Otherwise you'll have to manually recreate the fw rules for wan2.
Multiwan: Network > Multiwan checkout the bottom page to see samples of the settings. here's how i got mine setup:
a. I only have two internet connections so I always remove the last two wan interfaces. I also comment out MWAN3 and MWAN4 in /etc/iproute2/rt_tables (although it may not be necessary).
note: You'll get per connection distribution not per packet so don't expect one download to come from both gateways. Lots of talk on this in the internet. Failover = LoadBalancer for both links
6. Test.
try a torrent with lots of seeders. If you have a internet line that can do 90kbps max download, and another that can do 180kbps max if multiwan is working properly you should get a download rate greater than the higher rated link.
Unlike “channel bonding” or “link aggregation” which routes individual ethernet frames, multiwan routes individual sessions over the least busy WAN interface and that session continues to use the same WAN until terminated.
Note2: Multiwan (at least on Barrier Breaker r39404) does not accept WAN interfaces with “_” or other special characters
Основные настройки
В файле /etc/config/multiwan (по умолчанию маршрутизировать трафик через оба интерфейса WAN )
В командной строке (выставляем последовательный мониторинг живости линка):
* Распределение нагрузки посредством netfilter называется Fast Balancer (лучшее распределение)
* Распределение нагрузки посредством iproute2 называется Load Balancer (лучшая совместимость)
* Правило wanrule для Fast Balancer - “fastbalancer”
* Правило wanrule для Load Balancer - “balancer”
Казалось бы, что fastbalancer должен давать лучший результат, но в действительности Вам нужно попробовать оба варианта, чтобы понять, какой из них лучше всего подходит для вашей ситуации.
4. Troubleshooting
There's a problem if:
- Last modified: 2020/08/25 09:07
- by jamesmacwhite
Self-registration in the wiki has been disabled.
If you want to contribute to the OpenWrt wiki, please post HERE in the forum or ask on IRC for access.
Except where otherwise noted, content on this wiki is licensed under the following license:
CC Attribution-Share Alike 4.0 International
Если Вы используете несколько интернет соединений и хотите их соединить в один поток а также контролировать весь трафик Ваших соединений.
Mwan3 может иметь заголовки для определения уровня интерфейса в качестве главного или запасного канала, распределения нагрузки. Источником соединения могут быть разные интернет каналы которые могут быть и главными и запасными.
Mwan3 uses netfilter mark mask to be compatible with other packages (such as OpenVPN, PPTP VPN , QoS -script, Tunnels, etc) as you can configure traffic to use the default routing table.
Первый WAN интерфейс (wan)
Требования
Interface configuration
Name | Type | Required | Default | Description |
---|---|---|---|---|
interface name | string | yes | (none) | The OpenWrt interface name as shown in OpenWrt's Network > Interfaces list (if using a PPPoE interface, the interface name specified here should be the underlying OpenWrt interface name, not the “pppoe-…” interface name) |
enabled | boolean | yes | (none) | Should mwan3 run on this interface |
track_ip | list of ip addresses | no | (none) | The hosts to test if interface is still alive. If this value is missing the interface is always considered up |
reliability | number | no | 1 | Number of track_ip hosts that must reply for the test to be considered as successful. Ensure there are at least this many track_ip hosts defined or the interface will always be considered down |
count | number | no | 1 | Number of pings to send to each host with each test |
timeout | seconds | no | 4 | Number of seconds to wait for an echo-reply after an echo-request |
interval | seconds | no | 10 | Number of seconds between each test |
up | number | no | 5 | Number of successful tests to considered link as alive |
down | number | no | 5 | Number of failed tests to considered link as dead |
The primary reason to change the default settings is to shorten the time before an interface is failed-over (by reducing the ping interval and number of pings before the interface is down) or lengthen the time to avoid a false link failure report. Please note that if you change the timeout value on low bandwidth interfaces (e.g. 3g) or busy interfaces, that false time-outs can occur. A timeout value of less then 2 seconds is not recommended.
A typical interface section looks like this:
The routable loopback (self)
On routers with just one wan interface (and one default route), there is no issue on which source address to use for new initiated sessions. But with two or more wan interfaces you may wish to have control over this. Up until version 2.0, mwan3 did not respect the already set source address of router originated packets. Packets were load-balanced regardless of source address, based on configured user rules.
As of version 2.0 mwan3 does respect the already set source address. The advantage of this is that an applications can have control over which wan interface to use. The downside of this is that when an application does not specify which source address to use (most of the time) the kernel will pick a source address based on the routing table. In practice this means the default route with the lowest metric is used to determine which source address to use. So if you don't configure a routable loopback address with corresponding more preferred default route, all traffic originating from the router itself will leave the primary wan with the source address of that wan interface, regardless of configured user mwan3 rules.
Configuring a routable loopback with default route is easy:
After this all traffic originating from router itself (if no more specific route is found) will have source address of 192.168.1.1 (before NAT ). Extra advantage is that configuring mwan3 rules for router only traffic is much easier.
Настройка
Оборудование
A TP-LINK TL-WR1043ND hardware version 1.10 router (ar71xx platform) (tl-wr1043nd) using OpenWrt 12.09.
2. Configure VLANs and Network Interfaces
Ensure the CONNTRACK module is enabled in OpenWrt
mwan3 requires that the CONNTRACK module is enabled and active on its WAN interfaces.
If the interfaces are in the “wan” firewall zone, and the “Masquerading” option is enabled for the firewall zone, the CONNTRACK module is enabled by default already (this is the default OpenWrt configuration)
Пре-конфигурация
до установки рекомендуется провести пре-конфигурацию и тестирование ваших соединений. Это не обязательно, но способно упростить инсталляцию и избежать многих подводных камней после нее.
Mwan3 and IPv6
3. Configure WANs and multiwan
Multiwan:
Network > Multiwan checkout the bottom page to see samples of the settings. here's how i got mine setup:
a. I only have two internet connections so I always remove the last two wan interfaces. I also comment out MWAN3 and MWAN4 in /etc/iproute2/rt_tables (although it may not be necessary).
Failover = LoadBalancer for both links
Установка
Mwan3 опции командной строки
Здесь описаны некоторые cli команды для выяснения проблем или просмотра статуса Ваших соединений:
Интерфейс WAN
Имя параметра | Значение по умолчанию | Варианты значения | Описание |
---|---|---|---|
weight | 10 | disable/1-10 | Load Balancer Distribution |
health_interval | 10 | disable/5/10/20/30/60/120 | Health Monitor Interval in seconds |
icmp_hosts | ? | disable/dns/gateway/ | Health Monitor ICMP Host(s) |
timeout | ? | disable/1-5/10 | Health Monitor ICMP Timeout |
health_fail_retries | ? | 1/3/5/10/15/20 | Attempts Before WAN Failover |
health_recovery_retries | ? | 1/3/5/10/15/20 | Attempts Before WAN Recovery |
failover_to | ? | disable/balancer/fastbalancer/ | Failover Traffic Destination |
dns | auto | auto/ | DNS Server(s) |
При использовании двух или нескольких модемов 3G вам нужно добавить для каждого интерфейса WAN следующие правила в /etc/config/network:
With Command Line Interface (CLI)
General options
Name | Default | Options | Description |
---|---|---|---|
default_route | balancer | balancer/fastbalancer/ | Selects the default path for all unspecified traffic |
health_monitor | parallel | parallel/serial | Memory footprint related |
debug | 0 | 0/1 | Output debug to log |
lan_if | lan |
It seems that fastbalancer is superior to balancer in terms of stability but you will need to try each setting to see which works best for you.
WAN Interfaces
Name | Default | Options | Description |
---|---|---|---|
weight | 10 | disable/1-10 | Load Balancer Distribution |
health_interval | 10 | disable/5/10/20/30/60/120 | Health Monitor Interval in seconds |
icmp_hosts | ? | disable/dns/gateway/ | Health Monitor ICMP Host(s) |
timeout | ? | disable/1-5/10 | Health Monitor ICMP Timeout |
health_fail_retries | ? | 1/3/5/10/15/20 | Attempts Before WAN Failover |
health_recovery_retries | ? | 1/3/5/10/15/20 | Attempts Before WAN Recovery |
failover_to | ? | disable/balancer/fastbalancer/ | Failover Traffic Destination |
dns | auto | auto/ | DNS Server(s) |
Outbound Traffic Rules
In the case of duplicate rule entries, the last rule will take precedent.
Читайте также: