Как посмотреть нагрузку на диск linux
Перейти к содержимому

Как посмотреть нагрузку на диск linux

  • автор:

Как посмотреть нагрузку на диск linux

Как узнать нагрузку на диск в Linux (IOPS)

Статистику по операциям ввода-вывода для дисков можно посмотреть при помощи команд iostat и pidstat. Это поможет понять какие процессы создают набольшую нагрузку на диск в Linux.

Для работы с этими утилитами придется установить дополнительные пакеты. Инструкция по установка:
1) Debian\Ubuntu:

Команда iostat

Просмотр общей статистики ввода-вывода по дискам можно осуществить командой:

Пример вывода команды:

Важными столбцами являются:

  • r/s Число операций чтения с диска в секунду
  • w/s Число операций записи на диск в секунду
  • rkB/s Число прочитанных килобайт за секунду
  • wkB/s Число записанных килобайт за секунду

Команда pidstat

Просмотр статистики в разрезе процессов можно посмотреть в интерактивном режиме при помощи команды:

Top 15 tools to monitor disk IO performance with examples

Related searches: Linux Disk Usage. Top Storage monitoring tools. How to monitor Disk IO performance with examples. How to check disk read write usage on Linux. Check and monitor disk IO statistics and disk stats in Linux using iostat, vmstat and other tools. How to monitor disk IO by process ID for specific process in Linux. Storage monitoring tools. Get disk read write operation details in Linux with examples.

Top 15 tools to monitor disk IO performance with examples

In my earlier article I gave you an overview of different disk types (HDD, SSD, Optical Disks) and disk interface types (SATA, IDE, SAS, SCSI..) in details with pros and cons. Now in this article I will show you various tools along with examples to monitor disk IO performance in Linux environment.

1. iostat — Report Disk IO Statistics

isotat is part of sysstat rpm. You can install sysstat using yum or any other tool depending upon your environment.

iostat summarises per-disk I/O statistics, providing metrics for IOPS, throughput, I/O request times, and utilization. It can be executed by any user, and is typically the first command used to monitor disk io performance and investigate disk IO statistics and issues at the command line.

iostat provides many options for customizing the output. A useful combination is -dxz 1 , to show disk utilization only ( -d ), extended columns ( -x ), skipping devices with zero metrics ( -z ), and per-second output.

These columns summarize the workload applied. You can check iostat man page to understand the meaning of each column.

2. vmstat — Report virtual memory statistics

vmstat is another monitoring tool which is part of procps-ng rpm. It is most likely possible that procps-ng is installed by default on your Linux node or else you can also install it manually using yum

vmstat reports information about processes, memory, paging, block IO, traps, disks and cpu activity. Here we will use vmstat to monitor disk IO performance in Linux using -d for 1 second with 1 second interval.

To get summary disk IO statistics about disk activity

Follow man page of vmstat to get the complete list of supported arguments using which you can monitor your system resource.

3. iotop — Monitor disk IO Speed

iotop specialises in getting disk stats and is part of iotop rpm. You can install iotop using yum or any other tool depending upon your environment.

iotop watches disk I/O usage information output by the Linux kernel (requires 2.6.20 or later) and displays a table of current I/O usage by processes or threads on the system.

With —only iotop will only show processes or threads actually doing I/O, instead of showing all processes or threads so you can check and monitor disk IO performance.

4. nmon — Monitor System Stats

nmon is not available in the default repository of RHEL/CentOS. You can install if from the EPEL repository. To install the entire EPEL repo on RHEL/CentOS 7

and to install EPEL repo on CentOS/RHEL 8

Next you can install nmon using yum command

Alternatively you can also install nmon tool manually

nmon can display the CPU, memory, network, disks (mini graphs or numbers), file systems, NFS, top processes, resources (Linux version & processors) and on Power micro-partition information.

Execute nmon from the terminal

To only display disk usage statistics press D

To display disk usage statistics with graph press d

5. atop — Advanced System & Process Monitor

You can again install atop using yum (assuming you had installed EPEL repo) or alternatively you can manually install atop to check and monitor disk IO performance in Linux.

The program atop is an interactive monitor to view the load on a Linux system. You can use atop to monitor disk IO by process. It shows the occupation of the most critical hardware resources (from a performance point of view) on system level, i.e. cpu, memory, disk and network.

Now press shift + d for disk activity
Then press c for full command name..

6. collectl — Collects data that describes the current system status

collectl is not available in the internal repo of CentOS/RHEL, so either you can install EPEL repo itself and then use yum to install collectl or manually install it.

collectl will collect data that describes the current system status. We can use collectl to check and monitor disk IO performance in Linux. The following command reports CPU and disk IO statistics. Here c and d represent CPU and Disk.

Follow man page of collectl to see all the supported options.

7. sar — Monitor Disk IO Performance

sar is another famous and widely used too and is part of sysstat rpm. You can install sysstat using yum or any other tool depending upon your environment.

sar is a powerful tool which can be used to monitor all the system resources. But to stick to this article’s topic, we will use -d to monitor disk IO performance for 1 second with an interval of 1 second.

You can check this article to understand about all these columns and other options supported with sar and ksar .

8. blktrace — generate traces of the Disk I/O

blktrace is part of blktrace rpm which should be available in your default repository. You can install it using yum command or other tools based on your environment.

blktrace is a specialized utility for tracing block I/O events

Multiple event lines are printed for each I/O. You can also monitor disk IO by process. The columns are:

  • Device major, minor number
  • CPU ID
  • Sequence number
  • Action time, in seconds
  • Process ID
  • Action identifier (see blkparse(1)): Q == queued, G == get request, P == plug, M == merge, D == issued, C == completed, etc.
  • RWBS description (see the “rwbs” section earlier in this chapter): W == write, S == synchronous, etc.
  • Address + size [device]

At the end of execution you will get a summary of disk statswith throughput details of read and write operations.

Perf tools are performance analysis tools based on Linux perf_events (aka perf) and ftrace .

9. perf-tools: iolatency

iolatency — summarize block device I/O latency as a histogram and is part of perf-tools , you can download iolatency script from below location

Provide executable permission to the downloaded script

Next execute the script with -Q option which enables queued time. The -Q option includes the block I/O queued time, by tracing based on block_rq_insert instead of block_rq_issue :

Here the disk latency is between 16 — 32 milliseconds.

You can get some more examples on iolatency on the official github page

10. perf-tools: iosnoop — monitor disk IO by process

iosnoop is another tool from perf-tools . You can download iosnoop script from the below path

Provide executable permission to the downloaded script

It will trace disk I/O with details including latency. Here using -p I have provided the PID of cp command for which ionoop will show the latency value to monitor disk IO by process ID.

For more examples and list of supported options you can check the official github page

11. BPF Tools

Traditional Performance tools provide some insight for storage I/O, including IOPS rates, average latency and queue lengths, and I/O by process.

BPF tracing tools can provide additional insight for disk stats and can be used for disk IO performance in Linux.

Top 15 tools to monitor disk IO performance with examples

Credits: BPF Performance Tools

11.1 BPF Pre-requisite

You must install below rpms to be able to use BPF

  • bcc
  • bpftool
  • bpftrace

Here bcc can be installed from the system repository. Make sure bcc rpm version matches the loaded kernel version. So you can install both rpms together

Next install bpftools and bpftrace to be able to monitor disk IO performance

This will download the repo file and place at /etc/yum.repos.d/bpftools.repo . Now you can install bpftrace and bpftools using yum

11.2 biolatency

biolatency is a BCC and bpftrace tool to show disk IO statistics with latency as a histogram. The term device latency refers to the time from issuing a request to the device, to when it completes, including time spent queued in the operating system. We can use biolatency to check disk stats and monitor disk IO performance.

The -D option in biolatency shows histograms for disks stats separately, helping you see how each type performs.

This output shows disk IO statistics for /dev/sda , an internal disk, with I/O latency often between 128 and 4095 microseconds

11.3 biosnoop

biosnoop is a BCC and bpftrace tool that prints a one-line summary for each disk IO statistics.
It prints a line of output for each disk IO statistics, with details including latency (time from device issue to completion).

This allows you to examine disk IO performance in more detail:

The biosnoop columns are:

  • TIME(s): I/O completion time in seconds
  • COMM: Process name, if cached
  • PID: Process ID, if cached
  • DISK: Storage device name
  • T: Type: R == reads, W == writes
  • SECTOR: Address on disk in units of 512-byte sectors
  • BYTES: Size of the I/O
  • LAT(ms): Duration of the I/O from device issue to device completion

11.4 biotop

biotop is a BCC tool that is similar to top but to get disk stats and disk IO statistics in Linux.

  • -C: Don’t clear the screen
  • -r ROWS: Number of rows to print

Top of the list are kworker threads initiating writes: this is background write flushing, and the real process that dirtied the pages is not known at this point

11.5 bitesize

bitesize is a BCC and bpftrace tool to show the size of disk IO statistics.

This output shows the disk stats that both the kworker thread and jbd2 are calling I/O mostly in the 0 to 1 Kbyte range.

11.6 ext4slower

ext4slower traces the ext4 file system and checks disk IO performance for ext4 file system, and then only prints those disk stats that exceed a threshold.

Similar tools exist in bcc for other file systems: btrfsslower , xfsslower , and zfsslower . There is also fileslower , which works at the VFS layer and traces everything (although at some higher overhead).

Here I have a dd command running on another terminal to simulate artificial disk IO statistics

Conclusion

In this tutorial we learned about various Linux tools which can be used to check disk usage by different processes and monitor disk IO Performance. Disk read write plays very important role in how application data is processed between RAM and Disk so it is very important that you have disk with good I/O speed and RPM. I would recommend reading about different available disk types and disk interface types

This would give you an idea on choosing the type of drive which suits your requirement. In production environment we mostly prefer HDD over SSD due to cost and many other factors but for laptops and desktops mostly SSD are used. But now a days even in production environment is starting to move to SSD to support cloud environment.

Lastly I hope the steps from the article to monitor disk IO performance, disk stats and disk IO statistics in Linux was helpful. So, let me know your suggestions and feedback using the comment section.

References

I have used below external references for this tutorial guide
BPF Performance Tools

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

How can I monitor hard disk load on Linux?

Is there a good command line utility to monitor hard disk load on linux? Something like top but then monitoring disk activity i.s.o. cpu usage.

More specifically, I suspect that for some (heavy load) servers after several optimizations on various parts of the program(s) that run on it, right now the bottleneck is simply the logging to files on the disk. But I find it very difficult to assess how much traffic the servers can handle.

My ideal tool would be something that prints «You’re using 35% of your disk bandwidth right now». Any ideas?

Как отследить, какой процесс создаёт нагрузку на диск

Чрезмерная нагрузка на диск может быть вызвана такой причиной как заражение вирусом либо неправильная настройка программ. В любом случае, необходимо начать с идентификации процесса (программы), которая больше всего делает операций чтения и записи на диск.

iotop — аналог top для отслеживания нагрузки на диск в реальном времени

Программа top позволяет увидеть, какие процессы потребляют больше всего процессорного времени и оперативной памяти, но ничего не говорит об использовании процессами диска, об операциях чтения и записи на диск.

Программа iotop показывает скорость чтения и записи на диск, также процент использования файла подкачки каждым процессом.

Для установки iotop в Debian, Linux Mint, Kali Linux, Ubuntu и их производные выполните команду:

Для установки iotop в Arch Linux, BlackArch, Manjaro и их производные выполните команду:

Программа требует повышенных привилегий для запуска:

В выводе программы присутствуют следующие столбцы:

  • TID — идентификатор процесс
  • PRIO — приоритет процесса
  • USER — пользователь, который является владельцем процесса
  • DISK READ — скорость чтения диска
  • DISK WRITE — скорость записи на диск
  • SWAPIN — процент использования файла подкачки
  • IO> — процент от всех операций ввода-вывода
  • COMMAND — запустившая процесс команда

С помощью курсорных клавиш вправо () и влево () вы можете переключаться между столбцами, одновременно выбирая, по какому из них будет выполнятся сортировка.

С помощью кнопок «Home» и «End» вы можете переключаться между крайними столбцами.

Нажатие любой клавиши обновит окно.

Для выхода нажмите «q».

Нажав клавишу «o» вы переключитесь на показ только активных процессов, то есть только процессов, которые записывают и считывают данные с постоянного хранилища. Такой же результат вы можете получить запустив программу с опцией -o:

Повторное нажатие клавиши «o» вернёт показ всех процессов.

По умолчанию используется сортировка по убыванию, с помощью кнопки «r» вы можете переключаться между сортировкой по убыванию и по возрастанию.

Кнопка «p» переключает между показами процессов и потоков.

По умолчанию показываются скорости чтения и записи, с помощью кнопки «a» вы можете переключиться на показ общего количества записанных и прочитанных данных.

У iotop имеется несколько опций, которые позволяют управлять поведением программы, например следующая команда будет работать в пакетном режиме (-b), показывая общее количество записанных и прочитанных данных (-a) только для активных процессов (-o), к выводимым данным будет добавляться метка времени (-t), из всех процессов будет отфильтрована только информация о systemd-journald (grep 'systemd-journald'):

pidstat — вывод статистики для задач Linux

Пакет sysstat содержит сразу две утилиты с помощью которых можно собрать статистику использования диска процессами:

  • pidstat
  • iostat

Для установки pidstat в Debian, Linux Mint, Kali Linux, Ubuntu и их производные выполните команду:

Для установки pidstat в Arch Linux, BlackArch, Manjaro и их производные выполните команду:

Следующая команда будет выводить накопленную статистику за каждые 20 секунд, будут показаны только активные процессы (сделавшие операции чтения и записи на диск за указанный интервал), также будет показана полная команда, запустившая процесс. Для более полной статистики запустите программу с повышенными привилегиями:

Каждая строка будет иметь следующие столбцы:

  • Метка времени
  • UID — числовой идентификатор пользователя
  • PID — идентификатор процесса
  • kB_rd/s — количество килобайт в секунду которые были прочитаны по инициативе указанной задачи
  • kB_wr/s — количество килобайт в секунду которые были (или должны были быть) записаны по инициативе указанной задачи
  • kB_ccwr/s — количество килобайт, запись которых на диск была отменена задачей. Это может произойти, когда задача усекает грязный кэш страниц. В этом случае некоторые операции ввода-вывода, для которых была учтена другая задача, не будут выполняться
  • iodelay — задержка ввода-вывода
  • Command — команда, запустившая задачу

iostat — статистика использования устройств и разделов дисков

Утилита iostat также включена в пакет sysstat. Как можно догадаться из названия программы, она создаёт отчёты по статистике ввода/вывода для устройств и разделов. Её особенностью является то, что она показывает обобщённую статистику для всей системы, а также для отдельных носителей, не разбивая её на процессы. Программа iostat может пригодиться когда необходимо ответить на вопрос: «какой из постоянных носителей подвергается наибольшей нагрузке?».

Запуск программы без опций

выведет два блока информации:

  • отчёт по использованию ЦПУ
  • отчёт по использованию устройств

Раздел со статистикой использований устройств содержит следующие разделы:

  • Device — имя устройства или раздела, как оно указано в /dev
  • tps — указывает количество передач в секунду, отправленных на устройство. Передача — это запрос ввода-вывода к устройству. Несколько логических запросов можно объединить в один запрос ввода-вывода к устройству. Размер перевода является неопределённой величиной
  • kB_read/s — указывает объём данных, считанных с устройства, выраженный в количестве блоков (килобайт, мегабайт) в секунду. Блоки эквивалентны секторам и поэтому имеют размер 512 байт
  • kB_wrtn/s — указывает объём данных, записываемых на устройство, выраженный в количестве блоков (килобайт, мегабайт) в секунду
  • kB_dscd/s — указывает количество данных, отбрасываемых устройством, выраженное в количестве блоков (килобайт, мегабайт) в секунду
  • kB_read — общее количество прочитанных блоков (килобайт, мегабайт)
  • kB_wrtn — общее количество записанных блоков (килобайт, мегабайт)
  • kB_dscd — общее количество отброшенных блоков (килобайт, мегабайт)

Отчёт выводит для всей системы с момента её загрузки.

Поскольку по умолчанию данные выводятся в килобайтах, а современные объёмы информации, записываемой на диск, обычно кратны гигабайтом, что цифры трудны для восприятия. Для вывода чисел в удобных для восприятия единицах используйте опцию -h:

Опция -h является эквивалентом указания сразу двух опций —human и —pretty, поэтому если вы не в полной мере довольны видом выводимого отчёта, то попробуйте использовать эти опции по отдельности.

Для вывода максимальной полной информации, укажите опцию -x:

Если вам нужна информация только об устройствах, то используйте опцию -d:

Вы можете запустить команду указав время интервала (в секундах) и счётчик (количество отчётов) — в этом случае программа будет выводить информацию через заданный интервал:

Первый отчёт будет содержать информацию с момента загрузки системы, а последующие отчёты будут содержать информацию за период, прошедший с предыдущего отчёта.

Для поиска проблем, вы можете использовать следующую команду, которая непрерывно будет выводить информацию:

С помощью iostat вы можете следить за скоростью чтения и записи на всё устройство, а также выявлять отброшенные блоки.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *