В чем прелесть Gentoo: Мифы и реальность
В ходе прочтения этой статьи и комментариев к ней, у меня сформировалось стойкое ощущение, что большинство пользователей, использующих другие дистрибутивы, имеют не совсем верное представление о gentoo-like системах. Скорее всего виновато в этом само словосочетание «source-based».
Кто-то, услышав его, представляет при этом компьютер, дымящийся от усилий, прикладываемых при бесконечной компиляции очередной утилиты. Кто-то вспоминает dependency-hell, который поджидает нас при установке тарболов. Кто-то считает, что это дистрибутив для малолетних шк энтузиастов, готовых родину продать за ускорение системы и снижение времени загрузки на пару секунд. Некоторые бегут в шоке узнав про практически полное отсутствие графических средств администрирования.
Так как я считаю что данный дистрибутив сильно недооценен, и, как следствие, его использует меньше людей чем могло бы (а чем шире сообщество, тем лучше), я решил описать свою, возможно глубоко субъективную, позицию по данному вопросу и постараться убедить читателей, что дистрибутив вовсе не столь брутален и хардкорен, как могло показаться.
Все, конечно, просто… но не совсем.
- Без документации никуда. Вам придется немало прочесть, чтобы установить этот дистрибутив. Крайне желательно, чтобы она была прочитана на английском, т.к. русская версия не всегда имеет актуальную версию
- Консоль — наше все. Если у вас консолефобия, вам придется побороть себя. Она тут всегда и везде: установка, обновление, настройка, все это и многое другое.
- Если вам срочно понадобится переустановить систему, или поставить её на новую машину, то это может занять довольно много времени. Помните об этом, когда ставите gentoo в продакшн.
Скорость
Многие считают, что gentoo предоставит им огромный выигрыш в скорости работы программ. Но давайте посмотрим сами. На топовом железе и так все довольно шустро работает, за исключение bloatware-дистрибутивов, и, как правило, разница между дебиан и гентой не столь велика, чтобы заморачиваться в большинстве случаев. А на более слабом железе, где, казалось бы, и нужна оптимизация, выигрыш будет очень небольшой, в виду того, что не велика разница между набором инструкций вашего процессора, и, например i686.
Так что ускорение работы тут скорее от отключения ненужных фич и уменьшения размеров ПО. Также не надо забывать, что скорость эта будет куплена ценой скорости сборки и установки ПО. Последняя, впрочем, не столь большая, как кажется. Времена, когда переборка системы занимала дни, прошли. 🙂
Сложность
- Сообщество. Оно немаленькое, у него большая русскоговорящая диаспора. В виду сложности дистрибутива и его ориентированности на энтузиастов есть огромный шанс, что ваша проблема уже всплывала, а если и нет, то остается немаленькая вероятность, что вам смогут помочь её решить.
- После этого порога, когда вы поняли что к чему, пользование системой становится куда более простым и предсказуемым делом. В том числе это достигается путем закалки пользователя, как не страшно это звучит. В той же убунте мне все равно приходилось лазить в консоль, но там это было редко, и я успевал забывать некоторые нужные команды, это вызывало у меня некий разрыв шаблона. Я уж молчу о том, что не всегда нормально обновлялся конфиг, подправленный вручную.
Приложения и стабильность
- Установка всего этого многообразия происходит через утилиты emerge и eix. Замечательной чертой gentoo является действительно стабильная «стабильная ветка», совмещенная с возможностью безболезненной установки свежих версий нужных вам программ. В принципе, можно полностью сидеть на нестабильном ПО, просто зачем? И наоборот, зная, что какие-то версии плохо работают в моем случае, есть возможность не обновляться на них.
- В разрешение проблем с зависимостями вносят свой вклад система слотов, дающая возможность устанавливать множество версий одной библиотеки, и отключение зависимостей через отключение USE-флагов. Часто пугают необходимостью собирать ядро, но на самом деле в этом нет ничего сложного, и с помощью genkernel не требует какого-то особого мастерства.
- Те, кто заботится о
кармелицензионной чистоте, могут указать с какими лицензиями можно ставить ПО. - Rolling-релизы делают обновление более безболезненным.
- Утилита eselect поможет выставить ряд переменных среды, например, дефолтные питон и яву.
Заключение
Хочется сказать, что я ни в коем случае не хочу умалять заслуги других дистрибутивов. Многие, из описанных мной возможностей, присутствуют и в них, но…
Благодаря сложной установке и высокому порогу вхождения, gentoo обладает очень хорошей документацией и вики, что гарантирует, что пользователь, как минимум, натолкнется на существование большинства этих фич до того, как они ему понадобятся. А это ИМХО благо, ибо избавляет от стресса, который возникает при необходимости решить задачу, методов решения которой ты даже не представляешь. Рано или поздно в любом дистрибутиве ты попадешь в консоль. Приятно иметь под рукой привычные инструменты, способные решить твою проблему, а не искать их на форумах.
What Is Gentoo Linux And How To Install It
Nowadays, most Linux distributions provide precompiled packages. This means that the distribution builds the packages in the developer’s machine. While compiling packages is not necessarily an issue in today’s high-bandwidth world, there are a number of problems that should be considered in that distribution model:
Compiled binaries mean that you do not have control over how the program is being compiled and what features are included in the program.Relying on binaries means that you give your full trust to the distribution’s developers that they will not include malicious code in their repositories.
Why Use Gentoo?#
The reason is simple: Gentoo is a powerful Linux distribution. It gives you almost unrestricted access and freedom to change and modify the whole system.
Portage, the Heart of Gentoo#
Portage is the main component that manages a Gentoo Linux system. It installs, manages and tweaks third-party packages. Further, portage also manages basic system configurations. The main difference that Portage offers is that it allows you to install your packages from its source. While this is possible in other distributions, Portage takes it a step further and makes it the default means of obtaining packages.
Obtaining Gentoo#
You can obtain a copy of Gentoo from its website. In there, you can choose the installer from a number of different platforms. Gentoo supports both amd64 and arm64. With the downloaded ISO file, you can then use a USB writing program like balenaEtcher to create your bootable flash drive.
Installing Gentoo Linux#
Before we continue installing Gentoo, it is important to note that this process is entirely manual, which means a lot of commands will be executed along the way. As such, it is recommended that you not only consult this guide but also check Gentoo’s official handbook for further guidance during the installation. Stick your flash drive into your computer and boot it up. It will boot you into the Gentoo Installer screen.
Setting Up the Network Connection#
To install Gentoo, you need to be connected to the Internet. The installer will connect automatically on a wired connection. From there, run the following command to check whether you are online: If you need to connect to a wireless network, you need to set up wpa_supplicant, which will connect you to your wireless access point. Once done, you have to reload the dhcpcd daemon to start your network connection by running this command:
Partitioning the Hard Disk#
Next, you need to format the disk you want to install Gentoo on. Do that easily by using the fdisk command. Fdisk is a simple command-line disk partitioning tool. It allows you to partition your hard disk and set the amount of storage you want for your system. Initialize it by typing: If you are not sure of your existing disk partition structure, check it with the -l flag:
Using fdisk to Partition the Hard Disk#
Once inside fdisk, you need to first wipe the disk for any existing partitions. Do that by pressing G in the prompt. With that done, you need to create new partitions in the disk:
The + sign tells fdisk that you want the size to be relative to the first sector you have selected.The size is a number that you specify yourself.The last option tells fdisk whether that size is in GB, MB or KB.
Partitioning for a UEFI Gentoo System#
With that done, continue partitioning your disk. This process will largely depend on whether you are using a BIOS or UEFI system. If you are using a modern computer with relatively recent hardware, chances are that you are using a UEFI system. To create a UEFI-compatible disk, you need to first create an “EFI System” partition. This should be the first partition in your disk and around 100-256MB in size. With that done, set the type of that partition to “EFI System” by pressing T. This will tell fdisk that you want to change the type of the partition you just created. From there, it will ask which type you want to set the partition to. Type 1.
Partitioning the Rest of the Disk#
The next partition you have to make is the “/boot” partition where the Linux kernel and the bootloader will be saved. Ideally, this partition should be around 500M-1G. In my case, I am setting this partition to 1G. From there, create the SWAP partition: part of your hard disk that your RAM can access to dynamically swap its memory whenever it is running out of space. The general rule for the SWAP size is 1/2 to 2 times the amount of memory that you have in your system. My laptop currently has 8GB of memory installed, so I set my SWAP size to 16GB. Further, to properly set this partition as SWAP, set its type to “19.” Lastly, create the root partition where the rest of the system will be installed. To allocate the rest of the disk, just press Enter in the Last Sector option when creating a new partition. With that done, press P to check the partition table that just created. Press W to save your changes to disk.
Formatting the Disks in Gentoo#
The next step is to format your hard disk. First, format the EFI System partition as FAT by using the following command: This will create the FAT filesystem that the EFI system requires to boot. From there, create the filesystem for the “/boot” partition by using the simpler ext2 filesystem. Next, create and enable the SWAP partition to tell Gentoo that this partition can be used for swapping with live memory. To do that, run the following: Lastly, create an ext4 filesystem for the root partition by running the following command:
Downloading the Gentoo Stage 3 Tarball#
From there, mount the root partition you just created to the “/mnt/gentoo” directory because the installation will now be done in your machine’s hard disk. Once done, download the Stage 3 tarball from the gentoo.org website by using wget: This tarball contains all the programs you need to have a minimal Linux installation. Unpack it using tar:
Selecting a Download Mirror and Copying DNS Info#
Indicate where you want to download your packages for this system by running the mirrorselect command: This will open a TUI program where you can select the closest server location to you. From there, copy the repository file for Gentoo to your “/etc/portage” folder, which is a configuration file that contains the links to how Gentoo will download its packages: Lastly, copy the resolver information from your USB installer to the “/mnt/gentoo” directory to ensure that once you change the root directory to the hard disk, the network will still work. To do that, run this command:
Mounting the Device Files and Chrooting#
Begin mounting the special directories from the USB installer to the hard disk to make sure that once you have run chroot, the peripherals you are using still work. The last thing to do in the USB installer is to run the chroot command to move the base root directory from the USB to your hard disk:
Mounting the /boot partition and Updating Gentoo#
Mount the “/boot” partition to your Gentoo machine to ensure that when you install the kernel later that it will be saved in the correct place: Once that is done, update your Gentoo repositories to make sure you get the latest packages when you do the first system update: From here, emerge-webrsync will connect to the mirrors that you have selected and download the latest EBUILDS available for Gentoo.
Your First Gentoo System Update#
You can now update your system to match the latest EBUILDS by running this emerge command: This will ask emerge to check your Stage 3 packages to the ones that are currently on the Gentoo repository. Emerge will update the packages that it finds to have a more recent version. As such, this process will take a while, as Emerge will fetch and compile each and every package it needs to update.
Time Zone and Locales#
Next, you need to set up region-specific information, which includes both your time zone and system locale. To set the time zone to your area, find the closest location to you listed in the “/usr/share/zoneinfo” folder. From there, write it to your “/etc/timezone” file. For example, the closest location to me is “Asia/Manila”: Now set your locale for Gentoo will determine the default system language for the computer. To do this, edit the “/etc/locale.gen” file: From there, add the locale you want Gentoo to use. You can view the full listing of available locales by checking the “/usr/share/i18n/SUPPORTED” file. In my case, I want the system to use a U.S. English locale: Then run locale-gen to recreate your system locale.
Installing the Linux Kernel#
There are multiple ways to install the Linux Kernel in Gentoo. Either manually configure all of its features or use a pre-built one from the Gentoo developers. For our purposes, we are opting for the latter. To install the pre-built Linux kernel, install two things – the installkernel package and the kernel itself – by running the following command:
Configuring the fstab#
With the kernel installed, populate the fstab file: the file that tells Gentoo on startup which partitions to mount and where. Run this command to edit it: Indicate all of the partitions you created in fdisk. For example, in a UEFI system, your fstab file could look something like this:
Setting Up the Root Password#
From there, you want to set the root password for the system, as by default, the Stage 3 tarball sets a random password for the root account. If you do not add a password here, it would be impossible to access it once you reboot. To change the root password, run the following:
Installing Additional Tools#
Once done, install additional third-party tools you may need for your Gentoo system. For example, if you want both Ethernet and wireless connectivity, install the following: Further, you can install a system logger if you want to monitor the behavior of your system: You can also install the filesystem utilities for the most common filesystems you might interact with:
Installing the Bootloader#
From there, the final step in installing Gentoo is the bootloader, a simple program that sits between the BIOS and the Linux kernel. Its function is to instruct the BIOS to load the kernel, which then bootstraps the operating system. To install the GRUB Bootloader, run the following command: Once installed, run the following commands to properly initialize and configure GRUB: After that, all that is left to do is to unmount the USB installer and reboot the system by running the following: Once the system reboots, you will be greeted by your newly installed Gentoo Linux system. From there, start installing basic software and packages to build your own custom Linux distribution. However, if you are still not sure which desktop environment to install, check out our article on what we think are the best desktop environments on Linux.
1. Is there a way to speed up the compile times in Gentoo?#
Yes! You can massively speed up the compile times in Gentoo by adding a few values to your “/etc/portage/make.conf” file. For example, set this value to allow your computer to utilize most of its cores during program compilation:
2. My system did not boot up! It showed GRUB, but after booting up, it is just blank.#
This could be due to a number of things. One of the most common reasons is that your fstab file was not properly set up. Fix this by plugging in your USB installer and following the steps that we took to chroot to the hard drive.
Why you should use gentoo linux
I have been using gentoo linux for the better part of a year now, and it is the best linux experience I have ever had.
Gentoo is a linux distribution focused on optimization and customization. It is one of the lesser know, but still widely used disto’s, primarily popular under linux enthusiasts.
Compilation
One of the things that makes gentoo so efficient is that all packages in the repo’s are downloaded as source code. That means you will need to compile it on your own machine, that way you can easily configure which features you want to enable, and which you are never going to use. This results in binaries that are as small or big as you need them to be, and have better performance than packages with every feature enabled all the time.
Portage
The portage package manager is a tool that makes compiling these packages very easy. You can define a list of so called “use flags” to enable on every package, and adjust this list per package based on your needs.
For example, if you run an X11 display server, you probably don’t need support for the wayland protocol, then you just disable it. And when you want to switch to wayland, it is very easy to adjust your use flags, recompile every package that had something changed, and you are on your way.
Custom kernel
Another one of my favorite features of gentoo is that it is very easy, and highly encourage to compile your own kernel. This means you can adjust every setting in the kernel to your liking. That is done using a very nifty tool called “menuconfig”, this terminal utility lists every option there is to configure in the kernel in sorted menu’s.
There are two benefits of configuring your own kernel:
- Your system will be more optimized for your specific hardware. For example, if you don’t have an apple keyboard, you don’t compile support for it. Or if you have an AMD cpu, you optimize your kernel for that type. (I, for example, have got my idle ram usage (with an display server running) down to 200mb, by disabling most of the kernel features I don’t need.)
- You will learn so much about how the kernel is structured.
Learning
In my time using gentoo, I have learned so much about the structure and internals of a linux system. Because there is so much to configure, there is also a lot of to learn about your system. This is honestly the best thing about gentoo, and why I have not switched away from it ever since.
Gentoo’s wiki is also really good, better than the arch wiki, I would say. It is very detailed, when you need it. And the install guide gives you the perfect start in your gentoo journey.
Обзор Gentoo Linux
Многие из пользователей Linux слышали о таком дистрибутиве как Gentoo. И о том что работа с ним нечто сложное и непостижимое для обычного пользователя. Но на деле все совсем иначе. Gentoo один из не многих дистрибутивов который позволяет без особых усилий весьма гибко настроить систему, при этом сделать это быстро. Огромный набор программного обеспечения в репозиториях данного дистрибутива дает возможность не отвлекаться на подключение сторонних источников ПО. А система портов позволяет выбирать версию нужного ПО.
В формате обзора Gento linux мы постараемся на практике оценить возможности этого дистрибутива, и сделать идеальную персональную систему. Познакомимся с Portage, научимся избавляться от лишнего функциональность в программах, оптимизировать систему под железо. Мы не будем описывать процесс установки Gentoo, хотя по факту после прочтения этой статьи у вас не возникнет проблем с установкой, ибо разница не особо большая.
Гибкость Gentoo
Очень часто в интернете всплывают споры, дает ли Gentoo прирост в производительности. Тут на самом деле все предельно просто. Все зависит от того на сколько тонко вы настроили систему. Многие если не все пользователи Gentoo Linux заявляют что это самый гибкий дистрибутив, чем же обусловлена эта гибкость?
Во первых стоит начать с того что Gentoo это source-based дистрибутив, то есть все ПО распространяется не бинарными пакетами (как например deb или rpm), а в виде исходных кодов. Так же сама система пакетный менеджер (если его можно так назвать) напоминает по принципу работы пакетный менеджер в FreeBSD. В системе есть папка в которой находятся порты, а именно подпапки с .ebuild файлами. Это своеобразные скрипты, они указывают на то откуда качать файлы, как их компилировать, и куда раскладывать то что получилось в итоге. За счет такого подхода достаточно создать всего один ebuild для того что бы установить целый набор программ.
USE флаги
Стоит отметить то что при установке различного ПО в Gentoo, его функциональность можно расширить / сузить за счет использования USE флагов. Например хотим мы установить пакет WireShark, в стандартный набор поставки этой программы в различных дистрибутивах входит весьма приличный пакет дополнительного ПО, которым скорей всего мы и пользоваться то и не будем. В Gentoo за счет USE флагов можно собрать собственный WireShark, только с нужным функциональностью. Например нам нужен весь стек протоколов, и графический интерфейс на основе Qt. Достаточно включить все флаги кроме doc, doc-pdf и GTK.eq
Проверка USE с помощью equery
В итоге мы получим пакет который будет весить значительно меньше чем аналог для других дистрибутивов.
Флаги можно ставить глобально и локально. Рассмотрим два файла
/etc/portage/make.conf — Глобальный файл настроек portage, к нему мы сегодня будем обращаться очень часто, т.к именно он поможет нам выжать буквально все из нашей системы. В случае с USE флагами все просто, в строчке USE=» « мы можем указать какие флаги надо использовать для каждого пакета, например имеет смысл поставить туда systemd если в дальнейшем будет использоваться эта система инициализации, или же KDE если планируете работать с этой оболочкой. Важно знать что от флагов будут определятся зависимости для пакетов, соответственно чем больше флагов — тем больше будет зависимостей для ПО.
/etc/portage/package.use — Тут уже можно определить файлы настроек для каждого пакета отдельно, поддерживаются логические выражения. Например :
>=dev-lang/python-3.6.0 examples
<=dev-lang/python-2.7.0 -examples
В таком случае для python версии 3.6 или выше у нас будут устанавливаться примеры программ, а для 2.7 и ниже напротив, примеры будут игнорироваться. Стоит обратить внимание, для того что бы включить флаг достаточно внести его имя, а для того что бы жестко указать portage на игнорирование флага, поставить перед его именем «-«.
Так же можно указывать временные флаги, которые будут действовать единожды в процессе сборки.
USE=» <флаг> » emerge <пакет>
Оптимизация под целевую архитектуру
Помимо сокращения бинарных файлов методом изменения USE флагов, так же оптимизировать работу компьютера можно настройкой компилятора под целевую архитектуру.
Как это работает ? — Программы в репозиториях других дистрибутивов находятся в бинарном виде. Разработчики как правило собирают программы без оптимизации под архитектуру, так как их основная задача заставить работать программу на как можно большем количестве ПК. Gentoo же дает нам возможность собрать нужную нам программу под нужную нам архитектуру.
Для того что бы это сделать нам надо заглянуть в файл /etc/portage/make.conf , там нам нужно отредактировать пару пунктов.
CFLAGS — дописываем туда -martch=native или же название своей архитектуры , например -march=haswell
По сути этим можно было и ограничится, но мы будем выжимать все из системы. Добавим флаг -O2 , это «скажет» portage собирать программы с оптимизацией второго уровня. Стоит отметить что в некоторых источниках могут писать что чем больше число тем будет выше степень оптимизации, иногда люди ставят -O10 и больше, но GCC поддерживает только 4 уровня оптимизации, все что выше будет автоматически сброшено до 4.
Оптимизация процесса сборки
- MAKEOPTS — тут мы можем указать количество потоков во время сборки, рекомендуется использовать n Ядер + 1;
- Это сделает сборку ПО менее долгим процессом.
ACCEPT_LICENSE = «*» — даем portage разрешение на сборку программ под любой лицензией; - L10N = «ru» и LINGUAS = «ru ru_RU en» — во время сборки программ будет выполняться их локализация (если программа поддерживает это);
- FEATURES — тут мы можем указать разные «фичи» которые будет использовать portage во время своей работы. Например : userfetch — Во время загрузки файлов portage будет сбрасывать root привилегии, имеет смысл с точки зрения безопасности. parallel-fetch — Во время компиляции программ будут загружаться исходные коды, это ускорит время установки пакетов. candy — интересная анимация для emerge. fail-clean — очистка TMP после ошибки во время сборки. 2ccache — кешировние GCC, дает весьма заметный прирост во время сборки. Чем больше пакетов собираете — тем больше прирост скорости;
О других фичах можно прочитать в официальной Wiki проекта Gentoo. - VIDEO_CARDS — оптимизация ПО под вашу видеокарту , например =»i965 intel»;
- ACCEPT_KEYWORDS — выбор ветки portage. Например при
Пару советов по сборке ядра
- Прежде чем самому лезть в конфигуратор ядра, имеет смысл загуглить конфиг для сборки. Например мне, с моим T440P это сэкономило кучу времени. Как правило в таких конфигах имеет смысл проверить железо, и довести все до актуального состояния.
- Для конфигурировния ядра есть много способов, начиная от элементарного ручного (работа с файлом .config), заканчивая веб-конфигуработором. Но обычно во всех гайдах используется menuconfig, но никто не говорит о том что есть более удобные вариации, GTK — gconfig и Qt — xconfig.
- Заранее установите sys-kernel/linux-firmware , и в случае если потребуется сборка модуля которого нет в ядре (например iwlwifi.ucode), то стоит помнить что они находятся в /lib/firmware
- Если планируете накладывать патчи, то настоятельно рекомендую использовать sys-kernel/vanilla-sources, ибо именно под него пишутся эти самые патчи.
- Использование ccache во время сборки ядра поможет вам сэкономить уйму времени, ибо будут собираться только измененные части ядра.
- Рекомендуем прочитать эту статью о сборке ядра linux.
Полезные инструменты
- gentoolkit — Набор утилит для администрации Gentoo;
- layman — Инструмент для управления оверлеями;
- eix — Удобное приложение для поиска программ в portage;
- porthole — Графический интерфейс для portage, написан на GTK, в качестве бекэнда использует emerge;
Вывод
В этом обзоре Gentoo linux мы открыли для себя возможности тонкой настройки системы под конечного пользователя. Исходя из выше написанного можно сделать вывод что Gentoo действительно гибкая система. За счет флагов мы можем уменьшить бинарный файл, как следствие он будет быстрее выгружаться в оперативную память, и меньше занимать места на жестком диске. Тонкая настройка /etc/portage/make.conf дает заметный прирост в производительности.
Система Portage позволяет использовать несколько версий пакетов одновременно, что позволяет работать с самым стабильным ПО, даже если оно использует тестовые библиотеки. Так же мы рассмотрели несколько нюансов сборки ядра, и узнали про пару удобных инструментов для администрирования Gentoo. Так же советуем вам почитать о установке пакетов в Gentoo
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.