- Бонд. Джеймс Бонд или объединение сетевых интерфейсов (бондинг)
- Этап подготовки:
- Этап настройки:
- Bonding
- Shutdown / Unconfigure Existing Interfaces
- Configuration — Example 1
- Configuration — Example 2 («Laptop-Mode»)
- Configuration — Example 3 («Laptop mode», mostly as per documentation — Debian 9 «stretch»)
- Configuration — Example 4 — (very complex server setup) with LACP Bonded trunk and VLANs split out of the trunk, different MTU’s on the VLANs
- bridging the bond
- Using systemd-networkd
- Enabling systemd-networkd
- Configuring the bond device
- Add interfaces to the bond/lag
- Giving the bond an IP
- Actualise the settings
- enabling bridging for virtual machines
- udev renaming issue
- Testing / Debugging
- Debugging ifenslave
- Additional Note For Debian Lenny On Sparc
- Startup / Configure New Interfaces
- Change active slave
Бонд. Джеймс Бонд или объединение сетевых интерфейсов (бондинг)
Подобная статья уже была от автора AccessForbidden: «Объединение сетевых интерфейсов в linux».
Эта статья именно о настройке, и установке. Пишу её потому, что недавно столкнулся с проблемами установки и настройки бондинга.
Ситуация была такова: Был стааренький компьютер на четырёх-поточном пентиуме, с гигабайтом ОЗУ, и встроенным гигабитным интерфейсом на мат.плате. Он был мне как шлюзом, так медиацентром, и NAS’ом. Но вот, когда уже дома появилось N-ное количество девайсов (телевизор, смартфоны и компьютеры) пропускной способности начало не хватать. Но была у меня хорошая интеловская сетевая карточка (тоже гигабитная) и я решил погуглить на тему объединения интерфейсов
Вообще, Ethernet bonding (если быть точнее) — это объединение двух или более физических сетевых интерфейсов в один виртуальный для обеспечения отказоустойчивости и повышения пропускной способности сети. Или (простым языком говоря)Raid для сетевых карт. Только их «заточенность» на пропускную способность, на одинакового производителя- не важна
Ну, для начала, нужно убедится, нуждаетесь вы в этом или нет (скорее всего, если вы это читаете, значит вам это возможно нужно. ). Перед тем, как начнём, предупреждаю: делать нужно всё на сервере и от рута.
Итак, начнём!
Вставляем сет.карту, если не вставали. ну и подключаем к свитчу (коммутатору) или роутеру обе карты
Этап подготовки:
Теперь, нам нужно поставить ifenslave. на данный момент, актуальна версия 2.6. Ставим:
Теперь, нам нужно выключить интерфейсы, которые мы объединяем (в моём случае, это — eth0, eth1).
Ну и останавливаем сеть:
Этап настройки:
Теперь нам нужно настроить файл /etc/network/interfaces
(я лично пользуюсь «нано»).
Поскольку показываю, как делал я, у меня он
# The loopback network interface
auto lo
iface lo inet loopback
# The primary network interface
auto usb0
allow-hotplug usb0
iface usb0 inet dhcp
auto eth0
iface eth0 inet static
address 192.168.0.1
netmask 255.255.255.0
network 192.168.0.0
auto eth1
iface eth1 inet dhcp
И привёл я его к
# The loopback network interface
auto lo
iface lo inet loopback
# The primary network interface
auto usb0
allow-hotplug usb0
iface usb0 inet dhcp
iface bond0 inet static
address 192.168.0.1
netmask 255.255.255.0
network 192.168.0.0
slaves eth0 eth1
bond-mode balance-rr
bond-miimon 100
bond-downdelay 200
bond-updelay 200
Хочу обратить ваше внимание на:
Первое — если у вас dhcp сервер, то в /etc/default/isc-dhcp-server, в Interfaces я указал bond0. так и с остальными серверами.
Второе — тоже про dhcp. если у вас оный сервер, то в address, netmask, network bond’а0, указываем те же параметры что и у интерфейса на который до этого, работал dhcp
Третье — должен быть только bond0 (0 — в данном случае. Кстати, их может быть куча). Интерфейсы, которые мы объединили написав в строку slaves, мы убираем.
После сделанного пишем (в терминале уже):
Только его!
«включаем» сеть. Кстати на ошибки можно не обращать внимания. Они не критичны.
Можем перезагрузится.
bond0 Link encap:Ethernet HWaddr 00:16:e6:4d:5e:05
inet addr:192.168.0.1 Bcast:192.168.0.255 Mask:255.255.255.0
inet6 addr: fe80::216:e6ff:fe4d:5e05/64 Scope:Link
UP BROADCAST RUNNING MASTER MULTICAST MTU:1500 Metric:1
RX packets:33518 errors:0 dropped:0 overruns:0 frame:0
TX packets:30062 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:6687125 (6.3 MiB) TX bytes:17962008 (17.1 MiB)
eth0 Link encap:Ethernet HWaddr 00:16:e6:4d:5e:05
UP BROADCAST RUNNING SLAVE MULTICAST MTU:1500 Metric:1
RX packets:16630 errors:0 dropped:0 overruns:0 frame:0
TX packets:15031 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:3288730 (3.1 MiB) TX bytes:8966465 (8.5 MiB)
Interrupt:43 Base address:0x6000
eth1 Link encap:Ethernet HWaddr 00:16:e6:4d:5e:05
UP BROADCAST RUNNING SLAVE MULTICAST MTU:1500 Metric:1
RX packets:16888 errors:0 dropped:0 overruns:0 frame:0
TX packets:15031 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:3398395 (3.2 MiB) TX bytes:8995543 (8.5 MiB)
Interrupt:17 Memory:e1080000-e10a0000
Можно ещё добавлять интерфейсы bond0:0 и т.д.
Подходящий для вас режим, указывайте в /etc/network/interfaces в строке: bond-mode.
Источник
- Bonding
This article will show how to «bond» two Ethernet connections together to create an auto failover interface.
First install the ifenslave package, necessary to enable bonding:
Shutdown / Unconfigure Existing Interfaces
Sometimes, ifdown doesn’t work, in that case use ifconfig eth0 down.
Configuration — Example 1
Modify the /etc/network/interfaces file:
Configuration — Example 2 («Laptop-Mode»)
Tie cable and wireless network interfaces (RJ45/WLAN) together to define a single, virtual (i.e. bonding) network interface (e.g. bond0).
As long as the network cable is connected, its interface (e.g. eth0) is used for the network traffic. If you pull the RJ45-plug, ifenslave switches over to the wireless interface (e.g. wlan0) transparently, without any loss of network packages.
After reconnecting the network cable, ifenslave switches back to eth0 («failover mode»).
From the outside (=network) view it doesn’t matter which interface is active. The bonding device presents its own software-defined (i.e. virtual) MAC address, different from the hardware defined MACs of eth0 or wlan0.
The dhcp server will use this MAC to assign an ip address to the bond0 device. So the computer has one unique ip address under which it can be identified. Without bonding each interface would have its own ip address.
Modify the /etc/network/interfaces file:
Note: The configuration above has been found working on Debian 6 and later versions. The last verified version is Debian 9.8 (*). The configuration is somewhat contrary to the documentation of interfaces, ifup and ifenslave and the examples under /usr/share/doc/ifenslave/examples/.
Theoretically only the bond0 interface should have the auto attribute. ifup bond0 will bring up the slaves automatically (as documentation says). This is partially true but obviously the configuration options of the slaves are ignored. E.g. wlan0 is brought up without starting wpa_supplicant and the bond-primary setting of eth0 is ignored. (TODO: Is this a bug in ifenslave?)
It seems the slaves must be brought up before bond0 to include their configuration options. To do so via the /etc/init.d/networking script, their definitions must be before the bond0 definition and the auto attributes have to be set.
Of course, they must not be started again when bond0 starts. The option bond-slaves none disables this.
The options bond-master, bond-primary and bond-mode have to be repeated consistently for each slave.
There will be warnings «ifup: interface xyz already configured», but at least it works.
(*) With newer Debian versions the names of the network devices (may) have changed, depending on the upgrade path. Installations from scratch now use «predictable network interface names» (https://wiki.debian.org/NetworkConfiguration#Predictable_Network_Interface_Names). To find the names of your interfaces you will want to look here: $ ls /sys/class/net/
This document still uses the traditional names.
Configuration — Example 3 («Laptop mode», mostly as per documentation — Debian 9 «stretch»)
This is a way to bring up a laptop mode with automatic failover between wired and wireless, with wired preferred if both are available, based on the documentation. However, the documentation example is not complete and not fully correct. Specificly, the changes to the example (usr/share/doc/ifenslave/examples/ethernet+wifi) are:
the eth0 stanza is required, otherwise it will work initially, but bond0 will remove eth0 for good if the eth0 link goes back down after coming up once (like when going from wireless to wired and then back to wireless), instead of just disabling it until it’s link comes back up.
So here is the /etc/network/interfaces marvel:
If you use DHCP or some other service, you need to change the «bond0» stanza accordingly, but the other interfaces must remain «manual», as they aren’t supposed to get an IP address.
Configuration — Example 4 — (very complex server setup) with LACP Bonded trunk and VLANs split out of the trunk, different MTU’s on the VLANs
Example is Debian 10 with lots of hard-to-derive-from-man-pages syntax. You are NOT going to want this config on a desktop computer, this is likely only going to be used in a datacenter with a properly configured (w/LACP — aka 8021q) upstream network switch Example /etc/network/interfaces file:
bridging the bond
If you want to use the bond in a bridge, simply add the bridge lines as per normal to your /etc/network/interfaces file. Change the bond interface to manual and use it as the bridge interface. Here’s a sample bridged bond interfaces file:
Using systemd-networkd
This method does not use the package ifenslave which is mentioned above. If your computer is using systemd, and your network cards are currently working, you don’t need anything else.
Note that as is common on unix-type operating systems, case matters — «Bond» is different from «bond» and «Name» is not the same as «name».
Enabling systemd-networkd
If you are not currently using systemd-networkd, you need to enable it.
Configuring the bond device
Create a file ending in .netdev in /etc/systemd/network. Name this after the bonded interface name you want to use (e.g. bond1.netdev).
This example assumes 802.3ad or LACP bonding, for more information see the systemd.netdev manpage and/or the kernel documentation.
Most systems should work with 802.3ad and this is probably the mode you want as it has both network cards working together to give you double the throughput. However, if it doesn’t work in your case, you can try another mode, such as active-backup (used in the ifenslave example above).
Note that systemd is always creating a default bond0 interface with balance round robin mode and the mode can’t be changed. So to use any other mode create bond1 or another name for the interface. Interface bond0 with mode 802.3ad simply won’t work.
Add interfaces to the bond/lag
There are two ways you can do this. One is to create a .network file for each network interface plus one for the bonded network. The other is to describe the network interfaces in the bonded network’s file. Here we’ll use the latter method.
Create a file ending in .network in /etc/systemd/network using the same name as previously (e.g. bond1.network).
systemd-networkd uses a matching system to decide which interface to use. You could use name-based matching here if you like, but do not use mac-based matching as this could cause confusion with the bond changing mac addresses.
This example uses pci-id based matching. To find the addresses for your network cards, use:
then use that information to create the .network file.
Another option is to simply use the names of the network interfaces by replacing the Path= line with Name= . You can also use wildcards, and you can specify both/all devices in a single file:
Giving the bond an IP
Create a file ending in .network in /etc/systemd/network. The name (obviously) should not already be used. This tell systemd how to bring up the bonded network. For a static IP address, you could use:
For DHCP (e.g. for a laptop where you could use wireless and/or wired connections) try:
Actualise the settings
If your network was using /etc/network/interfaces before setting up the bonding, rename the file to stop it from being used:
At this point I recommend rebooting the system. This is the easiest way to clear out any previous network configurations and it tests that systemd-networkd starts as expected. The network should come up with bonding active. You can verify this with:
You should see 4 devices, lo, your two physical network interfaces (marked as «SLAVE»), and the bond1 device. Only the bond1 device should have an ip address. It should also be marked as «MASTER».
If you need to make further changes later, or fix problems with your current setup, from now on you can simply restart systemd-networkd after updating the /etc/systemd/network files.
enabling bridging for virtual machines
I’ve added this section because it’s not immediately obvious that your existing network bridge configuration probably won’t work with systemd-networkd. Prior to setting up my network bond, I was using the bridge utils to create a br0 device using /etc/network/interfaces. Since I’ve removed that file, I needed a new way to set up the bridge.
Fortunately systemd-networkd is multi-talented and quite adept at handling network bridges. All you need to do is define the bridge and give it the appropriate characteristics.
Like the bond0 device, you need to create a .netdev file to define the device. I created br0.netdev as follows:
Then I link it to the network bond I’d defined earlier using br0.network:
Finally, I change the management .network file to refer to br0 instead of bond1. Because the previous definitions have made bond1 a slave to br0, this results in the bridge being brought up properly.
udev renaming issue
You will likely only see UDEV rules for your network devices if you have upgraded from previous versions of Debian. New installations name the network cards after their pci addresses. The rules are used to preserve the legacy names for devices (e.g. eth0) in case they are being used elsewhere.
If you are confident that you are not using the legacy names, you can simply remove the file described below.
«udev» assign network adapter names as per
where rule typically looks like this:
The problem with bonding is that two or more NICs may have the very same MAC address which confuses udev when it tries to (re)name adapters as per their MACs and fails because another card with this MAC already exists. When it happens NIC may be left named like «rename2» instead of «eth0» etc.
Possible solution is to change udev rule to assign network interface names as per NICs PCI IDs instead of MAC addresses. This can be done by replacing
with something like
in the file «70-persistent-net.rules».
Corresponding PCI IDs can be found in dmesg:
Where one can look for line fragment like this:
But this is not recommended as it will not find, for example, wireless devices or devices not using legacy names.
The preferred alternative is to find PCI IDs using » lspci -D | grep Ether«:
Note that on modern systems, you can translate the PCI address to the network name by using the two middle numbers expressed in base10. In the above example, the controller 0000:04:00.0 would be enp4s00.
Testing / Debugging
In order to get some insight what is happening behind the scenes while experimenting a small script to show some information about the bonding device may be helpful.
Debugging ifenslave
The bonding mechanism is based on a kernel module named bonding which exposes its interface via the virtual /sys filesystem (e.g. /sys/class/net/bond0/*).
Setup and configuration is done in userland with shell-scripts:
- /etc/network/if-post-down.d/ifenslave
- /etc/network/if-up.d/ifenslave
- /etc/network/if-pre-up.d/ifenslave
These scripts are called on system initialization and shutdown (actually it is ifup which calls them). Their intention is to feed the kernel module with the appropriate parameters and settings.
If something with bonding fails at all (and the tip above doesn’t help) you may have a look what the scripts do step by step.
To enable verbose output, invoke ifup -a -v directly (instead of invoking /etc/init.d/networking). The -v option enables a log of all commands the scripts are executing. This gives at least a trace what is happening when.
Unfortunately this will not show the reactions of the kernel module (like possible error messages), because kernel (module) messages are reported via the syslog utility.
To get a real insight what is going on you have to do what is called invasive debugging. This means to add lines to the scripts at critical points to send a message to syslog.
Function sysfs_change_down in file /etc/network/if-pre-up.d/ifenslave
Additional Note For Debian Lenny On Sparc
(may be applicable on other architectures as well)
Without this file, you will get a warning when starting up the bonded interface similar to this:
Startup / Configure New Interfaces
And more, if you use a Lenny environment which has been upgraded from Etch, it is strongly recommended to check the result of the following command to check the bonding device mode, because configuration files for Etch and older versions do not work for Lenny and later releases.
1. Ping to other system in a terminal
2. Disconnect the active network cable and watch the ping result, the network should be resumed in few seconds
3. Reconnect the disconnected network cable, wait for 30 seconds to let the ARP table being updated
4. Disconnect another network cable and watch the ping result, the network should be resumed in few seconds
Change active slave
1. Use ifenslave to change the active slave. Below example will set eth0 as active slave
Источник