- 👍 Как оптимизировать производительность системы Linux с помощью tuned-adm
- Статическая настройка
- Динамическая настройка
- Установка Tuned
- Выбор профиля tuned
- Tuned – Automatic Performance Tuning of CentOS/RHEL Servers
- How to Install Tuned on CentOS/RHEL & Fedora
- How To Create Custom Tuning Profiles
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Тюнинг сетевого стека Linux для ленивых
- Чего нужно добиться?
- Рекомендации по подбору железа
- «Господи, я не хочу в этом разбираться!»
- network-top
- rss-ladder
- autorps
- server-info
- Прочие утилиты
- Господи, я хочу в этом разбираться!
- Обычные кейсы
- Пример 1. Максимально простой.
- Пример 2. Чуть сложнее.
- Необычные кейсы
- reterVision / notes.md
👍 Как оптимизировать производительность системы Linux с помощью tuned-adm
Как системный администратор, вы должны иметь возможность оптимизировать производительность системы Linux в соответствии с вашими рабочими нагрузками, регулируя различные параметры.
Э то руководство было написано для того, чтобы помочь вам оптимизировать производительность вашего сервера Linux с настройками.
Профиль | Назначение |
---|---|
balanced | Идеально подходит для систем, которые требуют компромисса между энергосбережением и производительностью. |
desktop | |
throughput-performance | |
latency-performance | |
network-throughput | Дополнительные параметры настройки сети применяются для максимальной пропускной способности сети. |
powersave | Статическая настройкаДинамическая настройкаПри динамической настройке настроенный демон отслеживает активность системы и корректирует настройки в зависимости от изменений поведения во время выполнения. Динамическая настройка непрерывно регулирует настройку в соответствии с текущей рабочей нагрузкой, начиная с начальных настроек, объявленных в выбранном профиле настройки. Установка TunedВ системе Linux RHEL / CentOS 8/7 пакет установлен и включен по умолчанию. Если вы хотите установить и включить пакет вручную на компьютере CentOS / RHEL, выполните команды: Подтвердите статус сервиса после его запуска. Выбор профиля tunedНастроенные профили делятся на следующие категории:
Мы будем использовать команду tuned-adm для изменения настроек демона tuned. Источник Tuned – Automatic Performance Tuning of CentOS/RHEL ServersTo maximize the end-to-end performance of services, applications and databases on a server, system administrators usually carry out custom performance tunning, using various tools, both generic operating system tools as well as third-party tools. One of the most useful performance tuning tools on CentOS/RHEL/Fedora Linux is Tuned. Tuned is a powerful daemon for dynamically auto-tuning Linux server performance based on information it gathers from monitoring use of system components, to squeeze maximum performance out of a server. It does this by tuning system settings dynamically on the fly depending on system activity, using tuning profiles. Tuning profiles include sysctl configs, disk-elevators configs, transparent hugepages, power management options and your custom scripts. By default tuned will not dynamically adjust system settings, but you can modify how the tuned daemon operates and allow it to dynamically alter settings based on system usage. You can use the tuned-adm command-line tool to manage the daemon once it is running. How to Install Tuned on CentOS/RHEL & FedoraOn CentOS/RHEL 7 and Fedora, tuned comes pre-installed and activated by default, but on older version of CentOS/RHEL 6.x, you need to install it using the following yum command. After the installation, you will find following important tuned configuration files.
Now you can start or manage the tuned service using following commands. Now you can control tuned using the tunde-adm tool. There are a number of predefined tuning profiles already included for some common use cases. You can check the current active profile with following command. From the output of the above command, the test system (which is a Linode VPS) is optimized for running as a virtual guest.
You can get a list of available tuning profiles using following command.
To switch to any of the available profiles for example throughput-performance – a tuning which results into excellent performance across a variety of common server workloads.
To use the recommended profile for your system, run the following command. And you can disable all tuning as shown. How To Create Custom Tuning ProfilesYou can also create new profiles, we will create a new profile called test-performance which will use settings from an existing profile called latency-performance. Switch into the path which stores sub-directories for all tuning profiles, create a new sub-directory called test-performance for your custom tuning profile there. Then create a tuned.conf configuration file in the directory. Copy and paste the following configuration in the file. Save the file and close it. If you run the tuned-adm list command again, the new tuning profile should exist in the list of available profiles.
To activate new tuned profile, issue following command. For more information and further tinkering options, see the tuned and tuned-adm man pages. That’s all for now! Tuned is a daemon that monitors usage of system components and dynamically auto-tunes a Linux server for maximum performance. If you have any questions or thoughts to share, use the feedback form below to reach us. If You Appreciate What We Do Here On TecMint, You Should Consider:TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all. If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation. We are thankful for your never ending support. Источник Тюнинг сетевого стека Linux для ленивыхСетевой стек Linux по умолчанию замечательно работает на десктопах. На серверах с нагрузкой чуть выше средней уже приходится разбираться как всё нужно правильно настраивать. На моей текущей работе этим приходится заниматься едва ли не в промышленных масштабах, так что без автоматизации никуда – объяснять каждому коллеге что и как устроено долго, а заставлять людей читать ≈300 страниц английского текста, перемешанного с кодом на C… Можно и нужно, но результаты будут не через час и не через день. Поэтому я попробовал накидать набор утилит для тюнинга сетевого стека и руководство по их использованию, не уходящее в специфические детали определённых задач, которое при этом остаётся достаточно компактным для того, чтобы его можно было прочитать меньше чем за час и вынести из него хоть какую-то пользу. Чего нужно добиться?Главная задача при тюнинге сетевого стека (не важно, какую роль выполняет сервер — роутер, анализатор трафика, веб-сервер, принимающий большие объёмы трафика) – равномерно распределить нагрузку по обработке пакетов между ядрами процессора. Желательно с учётом принадлежности CPU и сетевой карты к одной NUMA-ноде, а также не создавая при этом лишних перекидываний пакета между ядрами. Перед главной задачей, выполняется первостепенная задача — подбор аппаратной части, само собой с учётом того, какие задачи лежат на сервере, откуда и сколько приходит и уходит трафика и т.д. Рекомендации по подбору железаТаким образом, если дано 2+ источника объёма трафика больше 2 Гбит/сек, то стоит задуматься о сервере с числом процессоров и NUMA-нод, а также числу сетевых карт (не портов), равных числу этих источников. «Господи, я не хочу в этом разбираться!»И не нужно. Я уже разобрался и, чтобы не тратить время на то, чтобы объяснять это коллегам, написал набор утилит — netutils-linux. Написаны на Python, проверены на версиях 2.6, 2.7, 3.4, 3.6. network-topЭта утилита нужна для оценки применённых настроек и отображает равномерность распределения нагрузки (прерывания, softirqs, число пакетов в секунду на ядро процессора) на ресурсы сервера, всевозможные ошибки обработки пакетов. Значения, превышающие пороговые подсвечиваются. rss-ladderЭта утилита распределяет прерывания сетевой карты на ядра выбранного физического процессора (по умолчанию на нулевой). autorpsЭта утилита позволяет настроить распределение обработки пакетов между ядрами выбранного физического процессора (по умолчанию на нулевой). Если вы используете RSS, скорее всего вам эта утилита не потребуется. Типичный сценарий использования — многоядерный процессор и сетевые карты с одной очередью. server-infoДанная утилита позволяет сделать две вещи:
Прочие утилитыГосподи, я хочу в этом разбираться!Прочитайте статьи про: Эти статьи вдохновили меня на написание этих утилит . Также хорошую статью написали в блоге одноклассников 2 года назад. Обычные кейсыНо руководство по запуску утилит само по себе мало что говорит о том, как именно их нужно применять в зависимости от ситуации. Приведём несколько примеров. Пример 1. Максимально простой.
Пример 2. Чуть сложнее.
1 Переткнуть одну из 10 Гбит/сек сетевых карт в другой PCI-слот, привязанный к NUMA node1. 2 Уменьшить число combined очередей для 10гбитных портов до числа ядер одного физического процессора: 3 Распределить прерывания портов eth0, eth1 на ядра процессора, попадающие в NUMA node0, а портов eth2, eth3 на ядра процессора, попадающие в NUMA node1: 4 Увеличить eth0, eth1, eth2, eth3 RX-буферы: Необычные кейсыНе всегда всё идёт идеально:
Update: после публикации автор осознал, что люди используют не только RHEL-based дистрибутивы для сетевых задач, а тесты в debian на наборах данных, собранных в RHEL-based системах, не отлавливают кучу багов. Большое спасибо всем сообщившим о том, что что-то не работает в Ubuntu/Debian/Altlinux! Все баги исправлены в релизе 2.0.10 Update2. в комментариях упомянули то, что RPS всё же часто бывает полезен людям и я его недооцениваю. В принципе это так, поэтому в релизе 2.2.0 появилась значительно улучшенная версия утилиты autorps. Источник reterVision / notes.md1.1 Linux process management
A process is an instance of execution that runs on a processor. task_struct -> process descriptor Life cycle of processes parent process -> fork() -> child process -> exec() -> child process -> exit() -> zombie process -> parent process Kernel only assgins the new physical page to the child processes when the child process call exec() which copies the new program to the address space of the child process. The child process will not be completely removed unitl the parent process knows of the termination of its child process by the wait() system call. A thread is an execution unit generated in a single process. It runs parallel with other threads in the same process. Thread creation is less expensive than process creation because a thread does not need to copy resources on creation. Process priority and nice level Process priority is a number that determines the order in which the process is handled by the CPU and is determined by dynamic priority and static priority. Linux supports nice levels from 19(lowest priority) to -20(highest priority). During process execution, information on the running process is stored in registers on the processor and its cache. The set of data that is loaded to the register for the executing process is called the context. The interrupt handler notifies the Linux Kernel of an event. It tells the kernel to interrup process execution and perform interrup handling as quickly as possible because some device requires quick responsiveness. Interrupts cause context switching In a multi-processor environment, interrupts are handled by each processor. Binding interrupts to a single physical processor could improve system performance. Every process has its own state that shows what is currently happening in the process.
It is not possible to kill a zombie process with the kill command, because it is already considered dead. If you cannot get rid of a zombie, you can kill the parent process and then the zombie disappears as well. Process memory segments
Linux CPU scheduler two process priority arrays As processes are allocated a timeslice by the scheduler, based on their priority and prior blocking rate, they are placed in a list of processes for their priority in the active array. When they expire their timeslice, they are allocated a new timeslice and placed on the expired array. When all processes in the active array have expired their timeslice, the two arrays are switched, restarting the algorithm. 1.2 Linux memory architecture 32-bit architectures — 4 GB address space (3 GB usesr space and 1 GB kernel space) 64-bit architectures — 512 GB or more for both user/kernel space. Virtual memory manager Applications do not allocate physical memory, but request a memory map of a certain size at the Linux kernel and in exchange receive a map in virtual memory. VM does not necessarily have to be mapped into physical memory. If your app allocates a large amount of memory, some of it might be mmapped to the swap file on the disk subsystem. Applications usually do not write directly to the disk subsystem, but into cache or buffers. Page frame allocation A page is a group of contiguous linear addresses in physical memory (page frame) or virtual memory. A page is usually 4K bytes in size. The Linux kernel maintains its free pages by using a mechanism called a buddy system. The buddy system maintains free pages and tries to allocate pages for page allocation requests. It tries to keep the memory area contiguous. When the attempt of pages allocation fails, the page reclaiming is activated. Page frame reclaiming kswapd kernel thread and try_to_free_page() kernel function are responsible for page reclaiming. kswapd tries to find the candidate pages to be taken out of active pages based on LRU principle. The pages are used mainly for two purposes: page cache and process address space The page cache is pages mapped to a file on disk. The pages that belong to a process address space are used for heap and stack. swap If the virtual memory manager in Linux realizes that a memory page has been allocated but not used for a significant amount of time, it moves this memory page to swap space. The fact that swap space is being used does not indicate a memory bottleneck; instead it proves how efficiently Linux handles system resources. 1.3 Linux file systems Virtual file system VFS is an abstraction interface layer that resides between the user process and various types of Linux file system implementations. non-journaling file system fsck checks all the metadata and recover the consistency at the time of next reboot. But when the system has a large volume, it takes a lot of time to be completed. The system is not operational during this process journaling file system Writing data to be changed to the area called the journal area before writing the data to the actual file system. The journal area can be placed both in the file system or out of the file system. The data written to the journal area is called the journal log. It includes the changes to file system metadata and the actual file data it supported. The extended 2 file system is the predeceessor of the extended 3 file system.
Mode of journaling 1.4 Disk I/O subsystem Before a processor can decode and execute instructions, data should be retrieved all the way from sectors on a disk platter to the processor and its registers. The results of the executions can be written back to the disk. I/O subsystem architecture
Memory hierarchy L1 cache, L2 cache, L3 cache, RAM and some other caches between the CPU and disk. The higher the cache hit rate on faster memory is, the faster the access to the data. Locality of reference
Flushing a dirty buffer When a process changes data, it changes the memory first, so at the this time the data in memory and in disk is not identical and the data in memory is refered to as a dirty buffer. The dirty buffer should be synchronized to the data on the disk as soon as possible, or the data in memory could be lost if a suddden crash occurs. The synchronization process for a dirty buffer is called flush. kupdate — occurs on a regular basis. /proc/sys/vm/dirty_background_ratio — the propotion of dirty buffers in memory. The block layer handles all the activity related to block device operation. The bio structure is an interface between the file system layer and the block layer. Block sizes The smallest amount of data that can be read or written to a drive, can have a direct impact on a server’s performance. I/O elevator
I/O device driver 1.4 RAID and storage system 1.5 Network subsystem Networking implementation The socket provides an interface for user applications.
Socket buffer Network API(NAPI) The standard implementation of the network stack in Linux focuses more on reliability and low latency than on low overhead and high throughput. Gigabit Ethernet and modern applications can create thousands of packets per second, causing a large number of interruts and context switches to occur. For the first packet, NAPI works just like traditional implementation as it issues an interrupt for the first packet. But after the first packet, the interface goes into a polling mode. As long as there are packets in the DMA ring buffer of the network interface, no new interrupts will be caused, effectively reducing context switching and the associated overhead. Should the last packet be processed and the ring buffer be emptied, then the interface card will again fall back into the interrupt mode. NAPI also has the advantage of improved multiprocessor scalability by creating soft interrupts that can be handled by multiple processors. Netfilter You can manipulate and configure Netfilter using the iptables utility.
Netfilter Connection tracking
TCP/IP
Traffic control TCP/IP transfer window
Retransmission
Offload If the neetwork adapter on your system supports hardware offload functionality, the kernel can offload part of its task to the adapter and it can reduce CPU utilization.
Bonding module 1.6 Understanding Linux performance metrics Processor metrics
Memory metrics
Network interface metrics
Block device metrics
Источник |