Distcc pump linux kernel

distcc

distcc is a program to distribute builds of C, C++, Objective C or Objective C++ code across several machines on a network to speed up building. It should always generate the same results as a local build, is simple to install and use, and is usually much faster than a local compile. Further, one can use it together with native Arch build tools such as makepkg.

Contents

Terms

Getting started

Install the distcc package on all participating PCs in the distcc cluster. For other distros, or even operating systems including Windows through using Cygwin, refer to the distcc docs or the included man pages distcc(1) and distccd(1) . Be sure to allow traffic through the port on which distcc runs (the default is 3632/tcp), see Category:Firewalls.

Configuration

Modes of operation

Distcc can be run in plain mode (default) or in pump mode. At a high level, the key difference is in how distcc deals with preprocessed source. Plain mode transfers the complete source and compiler args. Preprocessing is kept on the client. Pump mode distributes both preprocessing and compilation to the distcc cluser which, in many cases, is more efficient and faster. See man distcc for more details.

Volunteers

The configuration for the volunteer is stored in /etc/conf.d/distccd . At a minimum, add the —allow-private switch which covers a number of ipv4 private network ranges. Logging to a file is also nice for troubleshooting if needed.

If multiple interfaces are present on the machine, consider passing the —listen ADDRESS option as well. Other options can be defined. Refer to distccd(1) .

Start distccd.service on every participating volunteer. To have distccd.service start at boot-up, enable it.

Client

For use with makepkg

Edit /etc/makepkg.conf in the following sections:

  1. The BUILDENV array will need to have distcc unbanged i.e. list it without exclamation point.
  2. Uncomment the DISTCC_HOSTS line and add the host name or IP addresses of the volunteers. Optionally, follow this with a forward slash and the max number of threads they are to use. The subsequent nodes should be separated by a white space. This list should be ordered from most powerful to least powerful (processing power).
  3. Adjust the MAKEFLAGS variable to correspond roughly twice the number max threads per server. In the example below, this is 2x(9+5+5+3)=44.

It should be noted that there are no true universal configurations. Try one, test it, compare the results to other setups. The following are a few common setups:

Plain mode example
Pump mode example

Several things to call out here:

  • Pump mode generally performs better with a high value for MAKEFLAGS than plain mode.
  • In pump mode, the IP or hostname is suffixed with a literal ‘,cpp,lzo’ as required by pump mode. Further, the localhost in this example was not. This means that distcc will load localhost with the 9 jobs defined and more aggressively distribute the code generation to the volunteers. It could be that in larger clusters, one might want to restrict the number of local jobs on the localhost to fewer to allow processing of distribution out to the cluster. One could also use the ,cpp,lzo suffix to the localhost as well.
  • As mentioned above, there is not a single configuration that will work efficiently with all distcc clusters/determining the optimal settings are derived empirically through testing and benchmarking.

For use without makepkg

Plain mode example

The minimal configuration for distcc on the client includes the setting of the available volunteers and re-defining the PATH .

Pump mode example

Compile

With makepkg

Plain mode example

No special steps are needed once /etc/makepkg.conf has been configured. Simply call makepkg as normal.

Pump mode example

The user must start pump prior to compiling whether with makepkg or on the shell. Since pump includes a check to make sure there is a set of DISTCC_HOSTS correctly configured, we need to first define a bogus DISTCC_HOSTS line. Remember that makepkg will use the values specified in /etc/makepkg.conf .

Now call makepkg as normal.

When finished, optionally stop pump:

Without makepkg

Plain mode example

After exporting the two variables describe in #For use without makepkg, simply call the compiler:

Some programs may require one to define the CC and/or CXX variable to work properly:

Читайте также:  Серверы удаленного доступа для linux

Pump mode example

Start pump as illustrated above. Compilation is no different than plain mode.

With CMake

Use the following CMake options to build a CMake-based project with distcc:

Monitoring progress

distcc ships with a cli monitor distccmon-text one can use to check on compilation status.

The cli monitor can run continuously by appending a space followed by integer to the command which corresponds to the number of sec to wait for a repeat query:

Cross compiling with distcc

One can use distcc to help cross compile.

  • A machine running the target architecture must be used as the client.
  • Non-native architecture volunteers will help compile but they require the corresponding toolchain to be installed and their distccd pointing to it.

Arch Linux ARM as clients (x86_64 as volunteers)

This section details how to use Arch Linux (x86_64) volunteers to help an Arch ARM device cross-compile. See these tests for evidence that speed gains on the order of 2-4x can be realized with just a single x86_64 machine helping an ARM device compile.

Volunteers

The Arch ARM developers highly recommend using the official project toolchains which should be installed on the x86_64 volunteer(s). Rather than manually managing these, the AUR provides all four toolchains as well as configuration and systemd service units:

Setup on the volunteer containing the arm/arm64 toolchains is identical to #Volunteers except that the name of the configuration and systemd service file matches that of the respective package. For example, for armv7h the config file is /etc/conf.d/distccd-armv7h and the systemd service unit is distccd-armv7h.service .

Note that each of the toolchains runs on a unique port thus allowing all four of them to co-exist on the volunteer if needed. Be sure to allow traffic to the port on which distcc runs see Category:Firewalls and distcc(1) .

Target architecture Distcc Port
armv5 3633
armv6h 3634
armv7h 3635
armv8h/aarch64 3636

Client

The easiest method to setup the Arch ARM client is to use distccd-arch-arm AUR . It provides all four configurations and systemd service units covering all four flavors of Arch ARM. For example, if the Arch ARM client is running an armv7h image, optionally edit /etc/conf.d/distccd-armv7h and change the defaults therein. When ready to build, enable distccd-armv7h.service and compile.

For a more detailed tutorial, see usage-examples.

If one would rather setup the client without using the AUR package mentioned above, manual setup of the client is identical to #Client except, one needs to modify the following two files to define the now non-standard port the volunteers are expected to use. Refer to the table above if using the AUR package.

  1. /etc/conf.d/distcc : example on an armv7h machine: DISTCC_ARGS=»—allow-private —log-level info —log-file /tmp/distccd-armv7h.log —port 3635″
  2. /etc/makepkg.conf : example on an armv7h machine: DISTCC_HOSTS=»192.168.10.2/5:3635 192.168.10.3/5:3635″
Note about localhost on ARM clients

When building on Arch ARM devices using x86_64 volunteers, it is highly recommended to exclude the localhost directive from DISTCC_HOSTS since many ARM devices do not have the needed processing power.

To illustrate this effect, consider the following example compiling the linux kernel version 5.10.44’s Image target. The client is a RPi4B (aarch64) and the volunteer (192.168.1.288) is a quad core/hyper threaded Intel machine. Each compile job was run only once and make clean was run in between them.

Running make -j15 Image CC=distcc CXX=distcc

DISTCC_HOSTS= Time (mm:ss) Fold slower
«192.168.1.288:3636/9» 6:50
«localhost/5 192.168.1.288:3636/9» 10:34 2.8x
«192.168.1.288:3636/9 localhost/5» 10:13 2.7x

Arch Linux (x86_64) as clients (Arch ARM as volunteers)

This section details how to use Arch ARM volunteers to help an x86_64 client cross-compile. See these tests for evidence that compilation times can be significantly sped up using even 1 Arch ARM volunteer and that up to 2 can double that gain.

Client

Setup of the client is identical to #Client with distcc running on the standard port 3632.

Volunteers

distccd-x86_64 AUR will provide a toolchain to install on the Arch ARM devices to enable cross compilation.

Additional toolchains

  • EmbToolkit: Tool for creating cross compilation tool chain; supports ARM and MIPS architectures; supports building of an LLVM based tool chain
  • crosstool-ng: Similar to EmbToolkit; supports more architectures (see website for more information)
  • Linaro: Provides tool chains for ARM development

The EmbToolkit provides a nice graphical configuration menu ( make xconfig ) for configuring the tool chain.

Troubleshooting

Quirks compiling the Arch Linux kernel package

If building the kernel from the official PKGBUILD (or many from the AUR), distcc will not work due to the fact that the kernel is hard-coded to use GCC plugins which cannot be supported by distccd due to technical reasons.

A workaround is to edit the kernel source removing the hard-coded requirement of GCC plugins. This can be accomplished with a sed one liner in the PKGBUILD itself inserted before the make step:

Failure to do this will result in distcc not working during the build. See FS#64275.

Читайте также:  Как записать windows power iso

Another option is to pass the CC=distcc and CXX=distcc variables as part of the build command:

Quirks compiling chromium

Compiling chromium which uses clang is currently affected by issue#386. In order to circumvent the bug, add the following to the _flags array in the PKGBUILD:

Journalctl

Use journalctl to find out what was going wrong:

Adjust log level

By default, distcc will log to /var/log/messages.log as it goes along. One trick (actually recommended in the distccd manpage) is to log to an alternative file directly. Again, one can locate this in RAM via /tmp. Another trick is to lower to log level of minimum severity of error that will be included in the log file. Useful if only wanting to see error messages rather than an entry for each connection. LEVEL can be any of the standard syslog levels, and in particular critical, error, warning, notice, info, or debug.

Either call distcc with the arguments mentioned here on the client or appended it to DISTCC_ARGS in /etc/conf.d/distccd on the volunteers:

Limit HDD/SSD usage by relocating $HOME/.distcc

By default, distcc creates $HOME/.distcc which stores transient relevant info as it serves up work for nodes to compile. This will avoid needless HDD read/writes and is particularly important for SSDs.

For distccd-alarm

No such file or directory

Errors similar to the following indicate that the user is mistakenly running the distccd service provided by distcc and NOT provided by the distccd-alarm packages (ie distccd-alarm-armv5 AUR , distccd-alarm-armv6h AUR , distccd-alarm-armv7h AUR , or distccd-alarm-armv8 AUR .)

Be sure to start the correct service for the target architecture.

Avahi-daemon stops publishing when distccd.service starts

The factual accuracy of this article or section is disputed.

Источник

Использование, настройка и тестирование distcc и ccache

Предистория:

Однажды мне пришла мысль проверить эффективность таких инструментов как distcc и ccache. Использовались они уже давно, но в голове все еще крутилась мысль о целесообразности этого всего. И вот наконец руки дошли проверить на практике, сразу предупреждаю что все делалось для себя, в реальных условиях, и результаты ваших тестов могут не совпадать с приведенными ниже. Рассмотрим установку и настройку этих компонентов, а затем проведем тестирование скорости сборки с помощью команды time.

Теория:

Для начала определимся что это такое и для чего может пригодится. Хотя если вы это читаете, то наверно уже понимаете для чего применяются эти инструменты.
Пару слов о Distcc из википедии.
Distcc (от англ. distributed C/C++/ObjC compiler) — инструмент, позволяющий компилировать исходные коды при помощи компиляторов C/C++/ObjC на удалённых машинах, что позволяет ускорить процесс компиляции.Состоит из двух основных частей — серверной (distccd) и клиентской (distcc).
Ccache (от англ. compiler cache; произносится «сикэш») — кэш компиляторов языка С и С++ для Linux и других Unix-подобных систем.
Использование ссache может значительно ускорить сборку некоторых пакетов или проектов, которые компилируются несколько раз, так как заново компилироваться будут только файлы, которые изменились с последней компиляции.

Что будем делать?

  1. Установим и настроим distcc и ccache.
  2. Проверим на сколько эффективно работают эти механизмы вместе, и по отдельности.

Имеется следующая инфраструктура: сеть 100 Mib/s, со следующими машинами:

Клиент distcc Сервер distcc Сервер distcc Сервер distcc
Процессор Intel Pentium Dual E2160 1.80GHz Intel Xeon 3.20GHz Intel Pentium D CPU 3.00GHz Intel Pentium 4 CPU 3.00GHz
Память 1 GB 1 GB 1 GB 1 GB
GCC 4.4.5 4.4.5 4.4.5 4.4.5
ОС gentoo x86 gentoo x86 debian 5.0.7 x86 debian 5.0.7 x86

Как видно машины довольно слабые, но со своими задачами справляются, на момент проведения тестов, все сторонние сервисы были отключены. Также, как можно было заметить, на всех машинах установлена одна версия GCC (рекомендуется использовать одинаковые версии, допускается различие в последней цифре версии 4.4.*) однако ранее на некоторых машинах также использовался GCC 4.4.3 и все прекрасно работало.

Установка и настройка:

Для начала необходимо установить и настроить наши инструменты.

Gentoo

Процесс установки distcc и ccache подробно описан в руководстве, я лишь кратко пройдусь по основным этапами, покажу некоторые нюансы.
Устанавливаем distcc:
emerge -avt distcc
Cмотрим на USE флаги, что нам надо оставляем, что не надо убираем и начинаем установку.
После того как distcc соберется и установится, параметры демона distccd будут находится в файле /etc/conf.d/distccd, список используемых хостов в /etc/distcc/hosts. В /etc/conf.d/distccd необходимо внести изменения в параметры сервера distccd.
Добавим возможность ведения логов, необходимо для отладки, в дальнейшем можно отключить:
DISTCCD_OPTS=»$ —log-file /var/log/distcc.log —log-level info »
Определим список хостов (сетей) чьи запросы мы будем обрабатывать:
DISTCCD_OPTS=»$ —allow 192.168.0.0/24″
Укажем интерфейс и порт на котором будет запущен демон:
DISTCCD_OPTS=»$ —listen 192.168.0.174″
Также есть возможность указать с каким приоритетом будет запущен сервис, это значение необходимо выставлять строго индивидуально, по умолчанию его значение 15:
DISTCCD_OPTS=»$ -N 15″
Необходимо сказать системе что можно использовать distcc, добавим в make.conf:
FEATURES=»distcc»
И определим директорию для временных файлов distcc:
DISTCC_DIR=»/tmp/.distcc»
Для тех кому не жалко памяти и хочется увеличить производительность, можно вынести каталог временных файлов на tmpfs (файловая система организовывается в виртуальной памяти (RAM+swap). Подходит для хранения временных файлов.)
mount -t tmpfs tmpfs -o size=850M /tmp/
В случае переполнения tmpfs данные будут писаться в swap что может негативно сказаться на производительности других программ.
Для постоянного использования добавим эту строчку в /etc/fstab:
tmpfs /tmp tmpfs size=850M,mode=0777 0 0

Читайте также:  Живые обои звездное небо для windows 10

Далее необходимо запустить сам сервис:
/etc/init.d/distccd start
И также можно добавить его в автозагрузку:
rc-update add distccd default

Напомню эти изменения мы вносили для серверной части distcc.
Теперь посмотрим что надо сделать на стороне клиента. Тут все просто, нам необходимо добавить список хостов, которые выступают в качестве серверов distcc, в файл /etc/distcc/hosts в одну строчку через пробел (указывать можно как имена машин так и их ip адреса). Перечисление машин рекомендуется начинать в порядке уменьшения мощности. Клиент может являться сервером, и наоборот.

Устанавливаем ccache по руководству
emerge -avt ccache
Cмотрим на USE флаги, что нам надо оставляем, что не надо убираем и начинаем установку.
После того как ccache соберется и установится, внесем изменения в /etc/make.conf.Скажем системе что необходимо использовать ccache:
FEATURES=»distcc ccache »
Установим размер кэша:
CCACHE_SIZE=»2G»
Определим место в котором будет находится кэш:
CCACHE_DIR=»/var/tmp/ccache»
Деррикторию с кэшем также можно хранить в tmpfs:
mount -t tmpfs tmpfs -o size=2G /var/tmp/ccache
или прописать в fstab:
tmpfs /var/tmp/ccache tmpfs size=2G,mode=0777 0 0
Однако в случае перезагрузки системы все данные в tmpfs будут утеряны, что сведет к нулю все наработки ccache.

Debian

Устанавливаем distcc. Так как клиентом будет машина с gentoo на борту, то на машинах с ОС Debian придется кое-что подправить.
Установим distcc и ccache:
apt-get install distcc
apt-get install ccache
Параметры демона distccd находятся в файле /etc/default/distcc, список используемых хостов находится в /etc/distcc/hosts.
Внесем изменения в /etc/default/distcc. Включаем запуск демона при загрузке машины:
STARTDISTCC=»true»
Указываем подсеть с которой слушаем запросы:
ALLOWEDNETS=»192.168.3.0/24″
Указываем адрес на котором сервис будет слушать порт:
LISTENER=»192.168.3.103″
Приоритет с которым будет работать запущенные процесс:
NICE=»15″
Включить или обнаружение через mDNS/DNS-SD
ZEROCONF=»false»
Значения в /etc/distcc/hosts заполняем также как на gentoo по необходимости (у меня debian используется только в качестве сервера distcc).
Теперь нам необходимо добавить символьную ссылку на используемую версию gcc, ссылка должна иметь имя исполняемого файла на клиенте (i686-pc-linux-gnu-c++):
cd /usr/bin/
ln -s ./g++-4.4 ./i686-pc-linux-gnu-c++
ln -s ./cpp-4.4 ./i686-pc-linux-gnu-cpp
ln -s ./gcc-4.4 ./i686-pc-linux-gnu-gcc
ln -s ./g++-4.4 ./i686-pc-linux-gnu-g++
Запустим сервер distcc:
/etc/init.d/distccd start
Следует пояснить что ссылки вроде i686-pc-linux-gnu-c++, следует создать, так как в клиентской системе (gentoo) при компиляции запускается жесткая ссылка с таким названием, которая также является gcc-4.4.
Также для достижения лучших результатов, я разместил каталог сборки для временных файлов в файловой системе tmpfs.

Тестирование

Теперь попробуем проверить эффективность на примерах. Для чистоты эксперимента сборка проводилась 3 раза. Собирать будем mplayer, просто первый под руку попался. Тестирование будем проводить с использованием утилиты time, которая на выходе дает следующие показатели:
user — общее количество секунд времени CPU, которое процесс провел в режиме пользователя.
sys — общее количество секунд времени CPU, которое процесс провел в режиме ядра.
real — фактически затраченное время (в секундах).

1 Сборка mplayer на локальном хосте без использования distcc и ccache (-distcc -ccache) с параметром -j2
time MAKEOPTS=»-j2″ FEATURES=»-distcc -ccache» emerge -vt mplayer

1 2 3
real 3m56.979s
user 6m11.729s
sys 0m44.551s
real 3m55.825s
user 6m12.151s
sys 0m43.660s
real 3m55.745s
user 6m12.351s
sys 0m43.671s

2 Сборка mplayer на локальном хосте без использования distcc и ccache (-distcc -ccache) с параметром -j3
time MAKEOPTS=»-j3″ FEATURES=»-distcc -ccache» emerge -vt mplayer

1 2 3
real 3m57.662s
user 6m15.214s
sys 0m43.392s
real 3m58.108s
user 6m14.779s
sys 0m43.656s
real 3m57.901s
user 6m14.894s
sys 0m43.464s

3 Сборка mplayer на локальном хосте без использования distcc, но с включенным ccache (-distcc ccache) с параметром -j2
time MAKEOPTS=»-j2″ FEATURES=»-distcc ccache» emerge -vt mplayer

1 2 3
real 4m14.438s
user 6m28.199s
sys 1m0.705s
real 0m58.587s
user 0m39.101s
sys 0m25.706s
real 0m57.901s
user 0m38.940s
sys 0m25.564s

4 Сборка mplayer на локальном хосте с использованием distcc, но без ccache (distcc -ccache) с параметром -j10
time MAKEOPTS=»-j10″ FEATURES=»distcc -ccache» emerge -vt mplayer

1 2 3
real 2m26.516s
user 1m6.692s
sys 0m34.821s
real 2m27.065s
user 1m6.643s
sys 0m34.856s
real 2m26.965s
user 1m6.593s
sys 0m34.569s

5 Сборка mplayer на локальном хосте с использованием distcc и ccache (distcc ccache) с параметром -j10
time MAKEOPTS=»-j10″ FEATURES=»distcc ccache» emerge -vt mplayer

1 2 3
real 2m28.590s
user 1m16.117s
sys 0m45.723s
real 0m57.456s
user 0m39.892s
sys 0m24.781s
real 0m57.411s
user 0m39.947s
sys 0m24.692s

Решил попробовать что-нибудь по тяжелее, ну например chromium

5 Собираем сначала на локальной машине без distcc и ccache.
time MAKEOPTS=»-j2″ FEATURES=»-distcc -ccache» emerge -vt chromium

1 2 3
real 67m30.435s
user 116m58.378s
sys 11m57.523s
real 66m50.345s
user 115m48.389s
sys 11m59.223s
real 67m45.165s
user 116m59.548s
sys 11m57.530s

6 Попробуем собрать с использованием distcc (distcc -ccache)
time MAKEOPTS=»-j10″ FEATURES=»distcc -ccache» emerge -vt chromium

1 2 3
real 36m25.392s
user 16m2.063s
sys 8m8.307s
real 35m15.291s
user 15m10.604s
sys 7m4.378s
real 35m22.390s
user 15m1.423s
sys 7m5.156s

7 Уже лучше, теперь попробуем тоже самое, но с использованием distcc и ccache.
time MAKEOPTS=»-j10″ FEATURES=»distcc ccache» emerge -vt chromium

Источник

Оцените статью