Advertisement
Open Source Projects by Phil Schwartz

Monitoring Linux disk I/O with Python

Linux already records disk activity for individual processes, but the useful information is buried in /proc. A Python tool can sample those counters, calculate differences over time and reveal which application is responsible for slow storage or excessive wear.

The key distinction is between logical and physical I/O. Character counters include data moving through pipes and terminals, while block-layer counters are closer to actual disk transfers. Neither figure is a perfect replacement for iostat, but together they provide a useful process-level view.

The resulting tool can help developers diagnose database checkpoints, package installations, backups and build jobs. It is especially handy on shared servers where several applications compete for the same storage device.

Australian infrastructure adds useful constraints: Sydney and Melbourne host major cloud regions, remote operations near Kalgoorlie may have limited bandwidth, and Perth does not observe daylight saving while eastern states do. Timing and offline reporting must therefore remain reliable.

Defining the metric

The /proc/PID/io interface exposes several cumulative counters. rchar and wchar measure bytes read and written through system calls, including non-disk activity. read_bytes and write_bytes track storage-facing traffic and generally provide a better starting point for disk analysis.

Cumulative values are not enough on their own. The tool needs to read each process twice, calculate the difference and divide it by the elapsed interval. A process that wrote 2 GB during a one-hour period is very different from one that wrote the same amount in ten seconds.

Building the sampler

The first version can use only the Python standard library. Each sample scans /proc, reads the available io files and stores the counters in memory. Errors are expected because processes can exit while being inspected.

import os
import time


def read_io(pid):
    values = {}
    with open(f"/proc/{pid}/io", encoding="ascii") as stream:
        for line in stream:
            key, value = line.split(":", 1)
            values[key.strip()] = int(value.strip())
    return values


def snapshot():
    result = {}
    for entry in os.scandir("/proc"):
        if not entry.name.isdigit():
            continue
        try:
            result[int(entry.name)] = read_io(entry.name)
        except (FileNotFoundError, PermissionError, ProcessLookupError):
            pass
    return result


before = snapshot()
time.sleep(1.0)
after = snapshot()

for pid, current in after.items():
    previous = before.get(pid)
    if previous is None:
        continue
    read_delta = max(0, current["read_bytes"] - previous["read_bytes"])
    write_delta = max(0, current["write_bytes"] - previous["write_bytes"])
    print(pid, read_delta, write_delta)

This prototype captures raw byte differences. It does not yet identify process names, detect PID reuse or distinguish temporary spikes from sustained activity. Those concerns become important once the sampler runs continuously.

Converting counters into rates

Use time.monotonic_ns() for intervals because the system clock can move backwards or jump during clock synchronisation. The reasoning behind precision execution timers applies here: wall-clock timestamps are useful for display, but monotonic measurements are safer for calculating durations.

Rates should also be labelled clearly. Bytes per second are useful for live monitoring, while totals explain how much data a job moved. Australian daylight-saving changes affect displayed timestamps in Sydney, Melbourne and Adelaide, but they have no effect on elapsed measurements taken with a monotonic clock.

Surviving Linux process quirks

A process may disappear between the two samples, and its PID may be reused by an unrelated program. A production sampler should capture the process start time from /proc/PID/stat and use the PID and start time together as its identity.

Permissions depend on kernel settings, user namespaces and container policies. Some /proc/PID/io files are readable only by the owner, while others require elevated privileges. Containers may also expose the host’s processes or a restricted namespace, so the tool should report when coverage is incomplete rather than presenting partial data as complete.

Making results easy to act on

A terminal view can show the command name, read rate, write rate and total transfer. Colour is helpful, but optional output such as CSV or JSON makes the results easier to combine with existing monitoring systems. Alert thresholds should use sustained values rather than a single sample.

Log-oriented analysis offers useful design ideas, as described in operational log analysis. In particular, storing timestamps with explicit time zones and retaining raw counters makes later investigations much easier than keeping only a transient rate.

Testing under realistic workloads

Start with predictable commands such as dd, fio and rsync, then compare the results with iostat and the system-wide totals in /proc/diskstats. Differences are normal because page caching, device drivers and network filesystems affect how work is attributed.

Useful test cases include SQLite writes, container image pulls, log rotation and package upgrades. A controlled test should also stop and restart a process rapidly to verify that disappearing PIDs and reused identifiers do not produce misleading entries.

Deployment recommendations

For the Australian market, a lightweight, self-hosted command-line tool with transparent licensing can be easier to justify than a per-host commercial agent, particularly for small engineering teams and organisations with remote sites.

The completed tool should remain deliberately modest: a sampler, a rate calculator and a clear output layer. That combination makes it practical for development servers, Australian cloud instances and offline edge systems where dependable visibility matters more than a large feature set.