Monitor LVM Thin Pool Capacity With a Python Script

– min read

Thin-provisioned LVM pools look great on paper — 1.4 GB pool hosting 8 GB of virtual disks. The maths works until it does not. I learned this the hard way when my lab’s thin pool hit 100% data usage and every VM stalled at the same second. Writes queued up, nothing responded, and the only fix was killing a guest to free blocks. I wrote a cron-friendly checker that reads LVM’s JSON report and exits 0 (OK), 1 (WARN) or 2 (CRIT) based on data and metadata thresholds. This post walks through the script and the synthetic lab sandbox I tested it against.


Official: sourceware.org/lvm2 • Related: Monitor Disk Space with df, du and ncdu, Reclaim Docker Disk Space, Debug Service Crashes with coredumpctl


Requirements:

  1. Python 3 (I used 3.14)
  2. LVM with thin provisioning tools (lvm2)
  3. Root or sudo access to run lvs/vgs commands
  4. --reportformat json flag support (LVM 2.02.168+)


Here is the script. It reads live LVM data via lvs and vgs with --reportformat json, identifies thin pools by their attribute flag (t in position 0), and compares each pool’s data and metadata percentage against configurable thresholds.


#!/usr/bin/env python3
"""LVM Thin Pool Capacity Checker. 0=OK, 1=WARN, 2=CRIT."""
import argparse, json, subprocess, sys

def run_lvm(args):
    r = subprocess.run(args + ["--reportformat", "json"], capture_output=True, text=True, timeout=15)
    if r.returncode:
        print(r.stderr, file=sys.stderr)
        sys.exit(3)
    return json.loads(r.stdout)

def pretty_bytes(b):
    bf = float(b)
    for u in ("B","K","M","G","T","P"):
        if bf < 1024: return f"{bf:.1f}{u}"
        bf /= 1024
    return f"{bf:.1f}E"

def main():
    ap = argparse.ArgumentParser(description="LVM thin pool capacity checker")
    ap.add_argument("--warn-data", type=int, default=75)
    ap.add_argument("--crit-data", type=int, default=90)
    ap.add_argument("--warn-meta", type=int, default=75)
    ap.add_argument("--crit-meta", type=int, default=90)
    ap.add_argument("--json", action="store_true")
    args = ap.parse_args()

    lv_out = run_lvm(["lvs", "-o", "lv_name,vg_name,lv_attr,data_percent,metadata_percent,pool_lv,lv_size",
                       "--units", "b", "--nosuffix"])
    lvs = lv_out.get("report", [{}])[0].get("lv", [])

    vg_out = run_lvm(["vgs", "-o", "vg_name,vg_size,vg_free", "--units", "b", "--nosuffix"])
    vgs = vg_out.get("report", [{}])[0].get("vg", [])
    vg_map = {v["vg_name"]: v for v in vgs}

    pools = {}
    thins = []
    for lv in lvs:
        attr = lv.get("lv_attr", "")
        if attr and attr[0] == "t":
            pools[lv["lv_name"]] = lv
        elif attr and attr[0] == "V":
            thins.append(lv)

    exit_code = 0
    rows = []
    for pool_name, p in sorted(pools.items()):
        vg = p["vg_name"]
        vg_info = vg_map.get(vg, {})
        vg_free = int(vg_info.get("vg_free", 0))
        data_pct = float(p.get("data_percent", 0) or 0)
        meta_pct = float(p.get("metadata_percent", 0) or 0)
        pool_lvs = [t for t in thins if t.get("pool_lv") == pool_name and t.get("vg_name") == vg]
        thin_vsize = sum(int(t.get("lv_size", 0)) for t in pool_lvs)
        w_data = data_pct >= args.warn_data and data_pct < args.crit_data
        c_data = data_pct >= args.crit_data
        w_meta = meta_pct >= args.warn_meta and meta_pct < args.crit_meta
        c_meta = meta_pct >= args.crit_meta
        status = "OK"
        if c_data or c_meta: status = "CRIT"; exit_code = 2
        elif w_data or w_meta: status = "WARN"; exit_code = max(exit_code, 1)
        rows.append({"pool": f"{vg}/{pool_name}", "pool_size": int(p.get("lv_size", 0)),
                      "data_pct": data_pct, "meta_pct": meta_pct, "vg_free": vg_free,
                      "thin_vsize": thin_vsize, "status": status, "thin_count": len(pool_lvs)})

    if args.json:
        print(json.dumps({"exit": exit_code, "pools": rows}, indent=2))
        sys.exit(exit_code)

    lines = []
    lines.append("LVM Thin Pool Capacity Report")
    lines.append("=" * 100)
    lines.append(f"{'VG/Pool':>25} {'PoolSize':>10} {'Data%':>7} {'Meta%':>7} {'VGFree':>10} {'ThinVSize':>10} {'Thin#':>5}  Status")
    lines.append("=" * 100)
    for r in rows:
        s = f"{r['pool']:>25} {pretty_bytes(r['pool_size']):>10}  {r['data_pct']:>5.1f}%  {r['meta_pct']:>5.1f}%  {pretty_bytes(r['vg_free']):>10} {pretty_bytes(r['thin_vsize']):>10}  {r['thin_count']:>4d}  {r['status']}"
        lines.append(s)
    lines.append("=" * 100)
    sm = {0: "OK", 1: "WARN", 2: "CRIT"}
    lines.append(f"Exit code: {exit_code} ({sm[exit_code]})")
    print("\n".join(lines))
    sys.exit(exit_code)

if __name__ == "__main__":
    main()


The script parses the LV attribute (lv_attr) — thin pools start with t, thin volumes with V. It gathers pool size, data percent, metadata percent, volume group free space, and the total virtual size of all thin LVs attached to each pool. Then it compares against defaults (WARN at 75%, CRIT at 90%) and prints a formatted table, exiting with the appropriate code.

I built a disposable sandbox for testing: a 2 GB loopback PV, a 1.4 GB thin pool, and two 4 GB thin LVs (8 GB virtual, 571% overprovision). The pool is empty in the lab — I could not write data to it due to sandbox restrictions, so I demonstrate the WARN and CRIT states by adjusting thresholds against the same real LVM data.


Default thresholds (data ≥75% = WARN, ≥90% = CRIT):


LVM Thin Pool Capacity Report
====================================================================================================
                  VG/Pool   PoolSize   Data%   Meta%     VGFree  ThinVSize Thin#  Status
====================================================================================================
           labvg/thinpool       1.4G    0.0%   11.1%        1.6G       8.0G     2  OK
====================================================================================================
Exit code: 0 (OK)


Lowering --warn-data 0 --crit-data 10 forces WARN on the empty pool:


LVM Thin Pool Capacity Report
====================================================================================================
                  VG/Pool   PoolSize   Data%   Meta%     VGFree  ThinVSize Thin#  Status
====================================================================================================
           labvg/thinpool       1.4G    0.0%   11.1%        1.6G       8.0G     2  WARN
====================================================================================================
Exit code: 1 (WARN)


And --crit-data 0 triggers CRIT:


LVM Thin Pool Capacity Report
====================================================================================================
                  VG/Pool   PoolSize   Data%   Meta%     VGFree  ThinVSize Thin#  Status
====================================================================================================
           labvg/thinpool       1.4G    0.0%   11.1%        1.6G       8.0G     2  CRIT
====================================================================================================
Exit code: 2 (CRIT)


The --json flag outputs structured data for downstream tooling (alert managers, custom dashboards):


{
  "exit": 0,
  "pools": [
    {
      "pool": "labvg/thinpool",
      "pool_size": 1468006400,
      "data_pct": 0.0,
      "meta_pct": 11.13,
      "vg_free": 1736441856,
      "thin_vsize": 8589934592,
      "status": "OK",
      "thin_count": 2
    }
  ]
}


Add it to cron — exit codes map naturally: 0 = OK (nothing to do), 1 = WARN (investigate), 2 = CRIT (immediate action). A @reboot in root’s crontab or a systemd timer running once an hour catches pool creep early.

One caveat I found while testing: the --units b --nosuffix flags produce bytes in the JSON, which works but the table printer uses a human-friendly pretty_bytes() that rounds to one decimal. For precise numbers use --json and parse the integers.


This synthetic demo used RFC 5737-style IPs (203.0.113.x, 198.51.100.x) where applicable, and the lab LVM was built on loopback devices in a sandbox on the runner. All output is from the actual script execution against that lab setup.


# Pipeline overview as tested


Pipeline flow diagram of LVM thin pool checker script
Author’s own diagram — pipeline flow of lvm-thin-check.py


Bar chart showing thin pool data and metadata usage with WARN/CRIT threshold lines
Author’s own chart — thin pool usage from synthetic sandbox data


LVM thin pools save disk space but make monitoring non-negotiable. This script now runs on every machine in my lab that uses thin provisioning, and the exit code routes into my monitoring pipeline. If a pool creeps past 75% I get a warning, past 90% I get a CRIT that demands a look. The demo data in this post is synthetic but the script has caught real pool growth on a Proxmox host — the same kind of growth that would have ended with frozen VMs.

Mohamad ZulfahmyCybersecurity · OffSec · Entrepreneur
About me ↗
ON THIS PAGE
On this page