lib.lvm

This library reads the LVM configuration of a host through lvs and vgs, and turns their report into the facts a consumer needs to judge it.

Both commands need root: /run/lvm and /run/lock/lvm are 0700 root, and /dev/mapper/control is 0600 root:root, so an unprivileged lvs exits 5 on the global lock and dmsetup cannot reach the driver at all. Membership of the disk group does not change that. Measured on Rocky 10 (lvm2 2.03.28) and Debian 13 (lvm2 2.03.31).

Both commands are asked for their report as JSON, which keeps the numbers on stdout and the warnings LVM writes to stderr out of the way. Each is a fixed argument list, so a sudo rule can spell the command out instead of ending in a wildcard. Every field they ask for, --reportformat json and --nosuffix among them, exists in lvm2 2.03.14 (the oldest still in service) and has not been renamed since.

The report is read one row per logical volume. A segment-level field such as segtype would turn that into one row per segment, so a volume spanning two physical volumes would be counted twice; lv_layout carries the same information per volume and is used in its place.

health() puts a value of lv_health_status into words. That field is the whole truth for a thin pool, a cache and a volume with a missing physical volume, and covers none of what happens to a classic snapshot: a snapshot the kernel threw away because its copy-on-write store ran full leaves lv_health_status empty and says so through lv_snapshot_invalid alone.

metadata_limit() answers at which fill level LVM stops creating thin volumes in a pool, which happens well before its metadata is full.

Typical use case:

volumes = lib.base.coe(lib.lvm.get_logical_volumes(timeout=8))
for lv in volumes:
    if lib.lvm.is_thin_pool(lv):
        print(lv['lv_full_name'], lv['data_percent'], lv['metadata_percent'])
  1#! /usr/bin/env python3
  2# -*- coding: utf-8; py-indent-offset: 4 -*-
  3#
  4# Author:  Linuxfabrik GmbH, Zurich, Switzerland
  5# Contact: info (at) linuxfabrik (dot) ch
  6#          https://www.linuxfabrik.ch/
  7# License: The Unlicense, see LICENSE file.
  8
  9# https://github.com/Linuxfabrik/lib/blob/main/CONTRIBUTING.md
 10
 11"""This library reads the LVM configuration of a host through `lvs` and `vgs`, and
 12turns their report into the facts a consumer needs to judge it.
 13
 14Both commands need root: `/run/lvm` and `/run/lock/lvm` are `0700 root`, and
 15`/dev/mapper/control` is `0600 root:root`, so an unprivileged `lvs` exits 5 on the
 16global lock and `dmsetup` cannot reach the driver at all. Membership of the `disk`
 17group does not change that. Measured on Rocky 10 (lvm2 2.03.28) and Debian 13
 18(lvm2 2.03.31).
 19
 20Both commands are asked for their report as JSON, which keeps the numbers on stdout
 21and the warnings LVM writes to stderr out of the way. Each is a fixed argument list,
 22so a sudo rule can spell the command out instead of ending in a wildcard. Every field
 23they ask for, `--reportformat json` and `--nosuffix` among them, exists in lvm2 2.03.14
 24(the oldest still in service) and has not been renamed since.
 25
 26The report is read one row per logical volume. A segment-level field such as
 27`segtype` would turn that into one row per *segment*, so a volume spanning two
 28physical volumes would be counted twice; `lv_layout` carries the same information
 29per volume and is used in its place.
 30
 31`health()` puts a value of `lv_health_status` into words. That field is the whole
 32truth for a thin pool, a cache and a volume with a missing physical volume, and
 33covers none of what happens to a classic snapshot: a snapshot the kernel threw away
 34because its copy-on-write store ran full leaves `lv_health_status` empty and says so
 35through `lv_snapshot_invalid` alone.
 36
 37`metadata_limit()` answers at which fill level LVM stops creating thin volumes in a
 38pool, which happens well before its metadata is full.
 39
 40Typical use case:
 41
 42.. code-block:: python
 43
 44    volumes = lib.base.coe(lib.lvm.get_logical_volumes(timeout=8))
 45    for lv in volumes:
 46        if lib.lvm.is_thin_pool(lv):
 47            print(lv['lv_full_name'], lv['data_percent'], lv['metadata_percent'])
 48"""
 49
 50import json
 51
 52from . import shell, time
 53from .globals import STATE_UNKNOWN, STATE_WARN
 54
 55__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
 56__version__ = '2026101201'
 57
 58# The fields read per logical volume, sorted, and every one of them a volume-level
 59# field so the report stays at one row per volume.
 60LV_FIELDS = (
 61    'data_percent',
 62    'lv_active',
 63    'lv_attr',
 64    'lv_check_needed',
 65    'lv_full_name',
 66    'lv_health_status',
 67    'lv_layout',
 68    'lv_merge_failed',
 69    'lv_metadata_size',
 70    'lv_name',
 71    'lv_role',
 72    'lv_size',
 73    'lv_snapshot_invalid',
 74    'lv_time',
 75    'lv_when_full',
 76    'metadata_percent',
 77    'origin',
 78    'pool_lv',
 79    'vg_name',
 80)
 81
 82# The fields read per volume group, sorted.
 83VG_FIELDS = (
 84    'lv_count',
 85    'pv_count',
 86    'snap_count',
 87    'vg_attr',
 88    'vg_extent_size',
 89    'vg_free',
 90    'vg_missing_pv_count',
 91    'vg_name',
 92    'vg_size',
 93)
 94
 95# Sizes are asked for in bytes without a unit suffix, so they arrive as plain numbers
 96# rather than as `4.00g` in whatever unit LVM felt like using.
 97LVS_COMMAND = (
 98    'lvs',
 99    '--reportformat',
100    'json',
101    '--units',
102    'b',
103    '--nosuffix',
104    '--options',
105    ','.join(LV_FIELDS),
106)
107
108VGS_COMMAND = (
109    'vgs',
110    '--reportformat',
111    'json',
112    '--units',
113    'b',
114    '--nosuffix',
115    '--options',
116    ','.join(VG_FIELDS),
117)
118
119# Every value `lv_health_status` can take, from `_lvhealthstatus_disp()` in
120# `lib/report/report.c`, put into the words somebody acting on it needs. `partial` is
121# tested before every other case in LVM itself, so a RAID volume whose leg has gone
122# missing reports `partial` and never `refresh needed`.
123#
124# `repair needed` and `refresh or repair needed` arrived in lvm2 2.03.39 (2026-03) and
125# exist in no earlier release: up to and including 2.03.38, a RAID leg the kernel has
126# marked dead is `refresh needed` whether its device is back or gone for good. Measured
127# on 2.03.28, where `vgreduce --removemissing` leaves a virtual error segment behind and
128# the volume still reports `refresh needed`. Both are carried here so a host on a newer
129# LVM is not reported as being in a state this does not know.
130HEALTH_LABELS = {
131    'error': 'the writecache is erroring',
132    'failed': 'the pool has failed and answers nothing',
133    'metadata_read_only': (
134        'the pool metadata is full, so the pool has gone read-only and every write to '
135        'it fails'
136    ),
137    'mismatches exist': 'a scrub found blocks whose copies disagree',
138    'out_of_data': (
139        'the pool is out of data space, so every write to a volume in it is queued and '
140        'then failed'
141    ),
142    'partial': 'one of the physical volumes it sits on is missing',
143    'refresh needed': 'a device came back and the array has not been refreshed onto it',
144    'refresh or repair needed': 'the array needs a refresh or a repair',
145    'repair needed': 'the array needs a repair',
146    'unknown': 'the state of the array could not be read',
147    'writemostly': 'a leg is marked write-mostly and is read from only as a last resort',
148}
149
150# How much free metadata LVM insists on before it will create another thin volume or
151# snapshot in a pool, from `thin_pool_metadata_min_threshold()` in
152# `lib/metadata/thin_manip.c`: the smaller of 4 MiB and a quarter of the metadata
153# volume. Measured on lvm2 2.03.28: at 75.10% of a 4 MiB metadata volume, `lvcreate`
154# refuses with "free space in thin pool reached threshold" while the pool itself is
155# still perfectly healthy.
156METADATA_HEADROOM_BYTES = 4 * 1024**2
157METADATA_HEADROOM_PERCENT = 25
158
159# How LVM renders `lv_time`, from the default of `report/time_format` in
160# `lib/config/defaults.h`. `%T` and the numeric offset are not locale-dependent, and
161# the commands run under `LC_ALL=C` anyway, so this parses on any host that has not
162# changed the setting.
163TIME_FORMAT = '%Y-%m-%d %H:%M:%S %z'
164
165# The three ways reading LVM fails, each opening the message it produces. What they
166# say is about the host and not about the check, which is why `failure_state()` rates
167# two of them as a problem to fix rather than as a check that could not run.
168NO_ANSWER = 'LVM did not answer'
169NOT_INSTALLED = 'The LVM tools are not installed on this host'
170NO_PERMISSION = 'LVM refused to report as this user'
171
172# What to tell somebody whose host has no LVM tools.
173NOT_INSTALLED_HELP = (
174    f'{NOT_INSTALLED}. Install them (`dnf install lvm2` on the Red Hat family, '
175    '`apt install lvm2` on the Debian family, `zypper install lvm2` on SUSE), or stop '
176    'reading LVM on this host.'
177)
178
179# What to tell somebody whose LVM did not answer. A command that reads LVM touches
180# every physical volume on the host, and one that does not answer puts it into an
181# uninterruptible sleep no signal ends. Naming a single volume group does not avoid
182# it, because the volume group is found by scanning all of them.
183NO_ANSWER_HELP = (
184    'LVM reads every physical volume on this host, so one of them that has stopped '
185    'answering blocks the whole command. `lsblk`, `dmesg` and the logs of the '
186    'storage transport say which device it is; `pvs` will answer again once it is '
187    'back or has been removed from the volume group with `vgreduce --removemissing`.'
188)
189
190# What to tell somebody who ran this without the rights it needs. LVM answers such a
191# run with an empty report and the lock file it could not open, which is worth naming
192# once here rather than quoting back on every run.
193NO_PERMISSION_HELP = (
194    f'{NO_PERMISSION}. Reading the volumes needs root, because `/run/lock/lvm` and '
195    '`/dev/mapper/control` are readable by root alone and no supplementary group '
196    'changes that. Run it through sudo, and deploy the sudoers rule that comes with '
197    'the check.'
198)
199
200
201def created(lv):
202    """
203    Read when a volume was created, as a UNIX epoch timestamp.
204
205    LVM renders `lv_time` with the pattern in `report/time_format`, whose default
206    (`%Y-%m-%d %T %z`) carries no locale-dependent part. A host that has changed the
207    setting, and a volume created before LVM started recording the time at all, yield
208    None rather than a wrong number.
209
210    Parameters
211    ----------
212    lv : dict
213        One row of `get_logical_volumes()`.
214
215    Returns
216    -------
217    float or None
218        The timestamp, or None where it could not be read.
219
220    Examples
221    --------
222    >>> created({'lv_time': '2026-08-27 11:19:13 +0200'})
223    1787822353.0
224    """
225    value = (lv.get('lv_time') or '').strip()
226    if not value:
227        return None
228    try:
229        return time.timestr2epoch(value, pattern=TIME_FORMAT)
230    except (TypeError, ValueError):
231        return None
232
233
234def failure_state(message):
235    """
236    Rate a failure to read LVM.
237
238    A host whose LVM has stopped answering, and one that carries no LVM tools although
239    something is asking it about its volumes, both have a problem that belongs on the
240    list of things to fix. Everything else - no rights, a report that will not parse -
241    is the reading that is broken and says nothing about the host, which is what
242    UNKNOWN is for.
243
244    Parameters
245    ----------
246    message : str
247        The message one of the reading functions returned.
248
249    Returns
250    -------
251    int
252        `STATE_WARN` or `STATE_UNKNOWN`.
253
254    Examples
255    --------
256    >>> failure_state('LVM did not answer within 8s. ...') == STATE_WARN
257    True
258    """
259    if (message or '').startswith((NO_ANSWER, NOT_INSTALLED)):
260        return STATE_WARN
261    return STATE_UNKNOWN
262
263
264def _diagnosis(stdout, stderr):
265    """
266    Pick the lines worth quoting out of a run that failed.
267
268    LVM puts its messages both on stderr and into the `log` array of the report, and
269    the report itself is the last thing worth printing back at somebody. This takes
270    the log messages where the report parses, falls back to stderr otherwise, and
271    keeps the result to one line.
272    """
273    lines = []
274    try:
275        for entry in json.loads(stdout).get('log') or []:
276            message = (entry.get('log_message') or '').strip()
277            if message:
278                lines.append(message)
279    except (AttributeError, TypeError, ValueError):
280        pass
281    if not lines:
282        lines = [line.strip() for line in (stderr or '').splitlines() if line.strip()]
283    return ' '.join(' '.join(lines).split())[:300]
284
285
286def _run(cmd, section, timeout):
287    """Run one LVM reporting command and read its report."""
288    success, result = shell.shell_exec(list(cmd), timeout=timeout)
289    if not success:
290        if 'Timeout after' in result:
291            return (False, f'{NO_ANSWER} within {timeout}s. {NO_ANSWER_HELP}')
292        if 'No such file or directory' in result:
293            return (False, NOT_INSTALLED_HELP)
294        return (False, result)
295    stdout, stderr, retc = result
296    if retc != 0:
297        # LVM writes warnings to stderr even on a successful run, so its text is only
298        # worth reporting where the command actually failed. What it failed at has to
299        # be read from that text and never from the exit code: `ECMD_FAILED` in
300        # `tools/errors.h` is 5 and covers every failure alike, so a volume group that
301        # does not exist and a run without the rights both end in 5. Measured on
302        # lvm2 2.03.28: `lvs no-such-vg`, `lvs -o no_such_field` and an unprivileged
303        # `lvs` all exit 5.
304        text = f'{stderr}{stdout}'
305        if 'Permission denied' in text or 'Running as a non-root user' in text:
306            return (False, NO_PERMISSION_HELP)
307        return (False, f'LVM did not report: {_diagnosis(stdout, stderr)}')
308    return parse_report(stdout, section)
309
310
311def get_logical_volumes(timeout=8):
312    """
313    Ask LVM for the logical volumes of this host.
314
315    Parameters
316    ----------
317    timeout : int, optional
318        Seconds the command is given. Defaults to 8.
319
320    Returns
321    -------
322    tuple
323        - On success: `(True, list)` - one dict per logical volume, keyed by the field
324          names in `LV_FIELDS`. An empty list means the host has no logical volume.
325        - On failure: `(False, error_message)`.
326
327    Examples
328    --------
329    >>> get_logical_volumes()
330    (True, [{'lv_full_name': 'vg0/root', 'lv_attr': '-wi-ao----', ...}])
331    """
332    return _run(LVS_COMMAND, 'lv', timeout)
333
334
335def get_volume_groups(timeout=8):
336    """
337    Ask LVM for the volume groups of this host.
338
339    Parameters
340    ----------
341    timeout : int, optional
342        Seconds the command is given. Defaults to 8.
343
344    Returns
345    -------
346    tuple
347        - On success: `(True, list)` - one dict per volume group, keyed by the field
348          names in `VG_FIELDS`. An empty list means the host has no volume group.
349        - On failure: `(False, error_message)`.
350
351    Examples
352    --------
353    >>> get_volume_groups()
354    (True, [{'vg_name': 'vg0', 'vg_size': '107369988096', 'vg_free': '0', ...}])
355    """
356    return _run(VGS_COMMAND, 'vg', timeout)
357
358
359def health(lv):
360    """
361    Say what is wrong with a volume, in one clause and without a subject.
362
363    Covers `lv_health_status` and the two states LVM reports beside it: a classic
364    snapshot the kernel threw away, and a snapshot whose merge back into its origin
365    failed. Both leave `lv_health_status` empty.
366
367    Parameters
368    ----------
369    lv : dict
370        One row of `get_logical_volumes()`.
371
372    Returns
373    -------
374    str
375        The clause, or an empty string when nothing is wrong.
376
377    Examples
378    --------
379    >>> health({'lv_health_status': 'out_of_data'})
380    'the pool is out of data space, so every write to a volume in it is queued and then failed'
381    """
382    if is_snapshot_invalid(lv):
383        return 'its copy-on-write store ran full and the kernel threw it away'
384    if lv.get('lv_merge_failed') == 'merge failed':
385        return 'merging it back into its origin failed'
386    if lv.get('lv_check_needed') == 'check needed':
387        return 'the pool is flagged as needing a check before it is used again'
388    status = lv.get('lv_health_status') or ''
389    if not status:
390        return ''
391    # An unknown value is reported rather than swallowed: LVM has added values to this
392    # field before, and a check that only knows the ones it was written against would
393    # report a volume in a state it does not recognise as healthy.
394    return HEALTH_LABELS.get(status, f'LVM reports it as "{status}"')
395
396
397def _roles(lv):
398    """Split `lv_role` into its parts."""
399    return (lv.get('lv_role') or '').split(',')
400
401
402def is_snapshot(lv):
403    """
404    Tell a snapshot, of either kind, from everything else.
405
406    Parameters
407    ----------
408    lv : dict
409        One row of `get_logical_volumes()`.
410
411    Returns
412    -------
413    bool
414
415    Examples
416    --------
417    >>> is_snapshot({'lv_role': 'public,snapshot,thicksnapshot'})
418    True
419    """
420    return 'snapshot' in _roles(lv)
421
422
423def is_snapshot_invalid(lv):
424    """
425    Tell whether the kernel has thrown a classic snapshot away.
426
427    This is the state a full copy-on-write store ends in. The origin keeps running,
428    the snapshot answers every read with an I/O error, and `lv_health_status` says
429    nothing about it.
430
431    Parameters
432    ----------
433    lv : dict
434        One row of `get_logical_volumes()`.
435
436    Returns
437    -------
438    bool
439
440    Examples
441    --------
442    >>> is_snapshot_invalid({'lv_snapshot_invalid': 'snapshot invalid'})
443    True
444    """
445    return lv.get('lv_snapshot_invalid') == 'snapshot invalid'
446
447
448def _layout(lv):
449    """Split `lv_layout` into its parts."""
450    return (lv.get('lv_layout') or '').split(',')
451
452
453def is_thin(lv):
454    """
455    Tell a thin volume from a thick one. A thin pool is not a thin volume.
456
457    Parameters
458    ----------
459    lv : dict
460        One row of `get_logical_volumes()`.
461
462    Returns
463    -------
464    bool
465
466    Examples
467    --------
468    >>> is_thin({'lv_layout': 'thin,sparse'})
469    True
470    """
471    layout = _layout(lv)
472    return 'thin' in layout and 'pool' not in layout
473
474
475def is_thin_pool(lv):
476    """
477    Tell a thin pool from every other volume.
478
479    Parameters
480    ----------
481    lv : dict
482        One row of `get_logical_volumes()`.
483
484    Returns
485    -------
486    bool
487
488    Examples
489    --------
490    >>> is_thin_pool({'lv_layout': 'thin,pool'})
491    True
492    """
493    layout = _layout(lv)
494    return 'thin' in layout and 'pool' in layout
495
496
497def metadata_limit(metadata_size):
498    """
499    Answer at which metadata fill level LVM refuses to create another thin volume or
500    snapshot in a pool.
501
502    LVM keeps back the smaller of 4 MiB and a quarter of the metadata volume, so the
503    limit is 75% for a metadata volume of 16 MiB or less and rises towards 100% for
504    larger ones. A pool that has reached it is fully functional and still cannot take
505    another snapshot, which is why it deserves an answer of its own rather than a flat
506    percentage everywhere.
507
508    Parameters
509    ----------
510    metadata_size : int or str
511        Size of the metadata volume in bytes, as
512        `lv_metadata_size` reports it.
513
514    Returns
515    -------
516    float or None
517        The limit in percent, or None where the size is unknown.
518
519    Examples
520    --------
521    >>> metadata_limit(4 * 1024**2)
522    75.0
523    >>> metadata_limit(64 * 1024**2)
524    93.75
525    """
526    size = to_number(metadata_size)
527    if not size:
528        return None
529    headroom = min(
530        METADATA_HEADROOM_PERCENT,
531        METADATA_HEADROOM_BYTES / size * 100,
532    )
533    return 100 - headroom
534
535
536def parse_report(stdout, section):
537    """
538    Read the rows out of an LVM JSON report.
539
540    Parameters
541    ----------
542    stdout : str
543        What the command printed on stdout.
544    section : str
545        The report section to read, `lv` or `vg`.
546
547    Returns
548    -------
549    tuple
550        - On success: `(True, list)` - one dict per row.
551        - On failure: `(False, error_message)`.
552
553    Examples
554    --------
555    >>> parse_report('{"report": [{"lv": [{"lv_name": "root"}]}]}', 'lv')
556    (True, [{'lv_name': 'root'}])
557    """
558    try:
559        data = json.loads(stdout)
560    except (AttributeError, TypeError, ValueError):
561        return (False, 'Unable to read the LVM report.')
562    # Valid JSON is not yet a report: `null`, a list or a report whose sections are
563    # not lists raised AttributeError or TypeError out of a function that returns a
564    # tuple. Anything but the documented shape is unreadable.
565    if not isinstance(data, dict) or not isinstance(data.get('report') or [], list):
566        return (False, 'Unable to read the LVM report.')
567    rows = []
568    for report in data.get('report') or []:
569        section_rows = report.get(section) if isinstance(report, dict) else None
570        if section_rows is None:
571            continue
572        if not isinstance(section_rows, list):
573            return (False, 'Unable to read the LVM report.')
574        rows.extend(row for row in section_rows if isinstance(row, dict))
575    return (True, rows)
576
577
578def to_number(value):
579    """
580    Read one value of an LVM report as a number.
581
582    LVM leaves a field that does not apply to a volume empty rather than reporting a
583    zero, so an empty percentage means "not measured here" and never "nothing used".
584
585    Parameters
586    ----------
587    value : str
588        The reported value.
589
590    Returns
591    -------
592    float or None
593        The number, or None where the field was empty or not a
594        number.
595
596    Examples
597    --------
598    >>> to_number('74.34')
599    74.34
600    >>> to_number('') is None
601    True
602    """
603    try:
604        return float(value)
605    except (TypeError, ValueError):
606        return None
LV_FIELDS = ('data_percent', 'lv_active', 'lv_attr', 'lv_check_needed', 'lv_full_name', 'lv_health_status', 'lv_layout', 'lv_merge_failed', 'lv_metadata_size', 'lv_name', 'lv_role', 'lv_size', 'lv_snapshot_invalid', 'lv_time', 'lv_when_full', 'metadata_percent', 'origin', 'pool_lv', 'vg_name')
VG_FIELDS = ('lv_count', 'pv_count', 'snap_count', 'vg_attr', 'vg_extent_size', 'vg_free', 'vg_missing_pv_count', 'vg_name', 'vg_size')
LVS_COMMAND = ('lvs', '--reportformat', 'json', '--units', 'b', '--nosuffix', '--options', 'data_percent,lv_active,lv_attr,lv_check_needed,lv_full_name,lv_health_status,lv_layout,lv_merge_failed,lv_metadata_size,lv_name,lv_role,lv_size,lv_snapshot_invalid,lv_time,lv_when_full,metadata_percent,origin,pool_lv,vg_name')
VGS_COMMAND = ('vgs', '--reportformat', 'json', '--units', 'b', '--nosuffix', '--options', 'lv_count,pv_count,snap_count,vg_attr,vg_extent_size,vg_free,vg_missing_pv_count,vg_name,vg_size')
HEALTH_LABELS = {'error': 'the writecache is erroring', 'failed': 'the pool has failed and answers nothing', 'metadata_read_only': 'the pool metadata is full, so the pool has gone read-only and every write to it fails', 'mismatches exist': 'a scrub found blocks whose copies disagree', 'out_of_data': 'the pool is out of data space, so every write to a volume in it is queued and then failed', 'partial': 'one of the physical volumes it sits on is missing', 'refresh needed': 'a device came back and the array has not been refreshed onto it', 'refresh or repair needed': 'the array needs a refresh or a repair', 'repair needed': 'the array needs a repair', 'unknown': 'the state of the array could not be read', 'writemostly': 'a leg is marked write-mostly and is read from only as a last resort'}
METADATA_HEADROOM_BYTES = 4194304
METADATA_HEADROOM_PERCENT = 25
TIME_FORMAT = '%Y-%m-%d %H:%M:%S %z'
NO_ANSWER = 'LVM did not answer'
NOT_INSTALLED = 'The LVM tools are not installed on this host'
NO_PERMISSION = 'LVM refused to report as this user'
NOT_INSTALLED_HELP = 'The LVM tools are not installed on this host. Install them (`dnf install lvm2` on the Red Hat family, `apt install lvm2` on the Debian family, `zypper install lvm2` on SUSE), or stop reading LVM on this host.'
NO_ANSWER_HELP = 'LVM reads every physical volume on this host, so one of them that has stopped answering blocks the whole command. `lsblk`, `dmesg` and the logs of the storage transport say which device it is; `pvs` will answer again once it is back or has been removed from the volume group with `vgreduce --removemissing`.'
NO_PERMISSION_HELP = 'LVM refused to report as this user. Reading the volumes needs root, because `/run/lock/lvm` and `/dev/mapper/control` are readable by root alone and no supplementary group changes that. Run it through sudo, and deploy the sudoers rule that comes with the check.'
def created(lv):
202def created(lv):
203    """
204    Read when a volume was created, as a UNIX epoch timestamp.
205
206    LVM renders `lv_time` with the pattern in `report/time_format`, whose default
207    (`%Y-%m-%d %T %z`) carries no locale-dependent part. A host that has changed the
208    setting, and a volume created before LVM started recording the time at all, yield
209    None rather than a wrong number.
210
211    Parameters
212    ----------
213    lv : dict
214        One row of `get_logical_volumes()`.
215
216    Returns
217    -------
218    float or None
219        The timestamp, or None where it could not be read.
220
221    Examples
222    --------
223    >>> created({'lv_time': '2026-08-27 11:19:13 +0200'})
224    1787822353.0
225    """
226    value = (lv.get('lv_time') or '').strip()
227    if not value:
228        return None
229    try:
230        return time.timestr2epoch(value, pattern=TIME_FORMAT)
231    except (TypeError, ValueError):
232        return None

Read when a volume was created, as a UNIX epoch timestamp.

LVM renders lv_time with the pattern in report/time_format, whose default (%Y-%m-%d %T %z) carries no locale-dependent part. A host that has changed the setting, and a volume created before LVM started recording the time at all, yield None rather than a wrong number.

Parameters
Returns
  • float or None: The timestamp, or None where it could not be read.
Examples
>>> created({'lv_time': '2026-08-27 11:19:13 +0200'})
1787822353.0
def failure_state(message):
235def failure_state(message):
236    """
237    Rate a failure to read LVM.
238
239    A host whose LVM has stopped answering, and one that carries no LVM tools although
240    something is asking it about its volumes, both have a problem that belongs on the
241    list of things to fix. Everything else - no rights, a report that will not parse -
242    is the reading that is broken and says nothing about the host, which is what
243    UNKNOWN is for.
244
245    Parameters
246    ----------
247    message : str
248        The message one of the reading functions returned.
249
250    Returns
251    -------
252    int
253        `STATE_WARN` or `STATE_UNKNOWN`.
254
255    Examples
256    --------
257    >>> failure_state('LVM did not answer within 8s. ...') == STATE_WARN
258    True
259    """
260    if (message or '').startswith((NO_ANSWER, NOT_INSTALLED)):
261        return STATE_WARN
262    return STATE_UNKNOWN

Rate a failure to read LVM.

A host whose LVM has stopped answering, and one that carries no LVM tools although something is asking it about its volumes, both have a problem that belongs on the list of things to fix. Everything else - no rights, a report that will not parse - is the reading that is broken and says nothing about the host, which is what UNKNOWN is for.

Parameters
  • message (str): The message one of the reading functions returned.
Returns
  • int: STATE_WARN or STATE_UNKNOWN.
Examples
>>> failure_state('LVM did not answer within 8s. ...') == STATE_WARN
True
def get_logical_volumes(timeout=8):
312def get_logical_volumes(timeout=8):
313    """
314    Ask LVM for the logical volumes of this host.
315
316    Parameters
317    ----------
318    timeout : int, optional
319        Seconds the command is given. Defaults to 8.
320
321    Returns
322    -------
323    tuple
324        - On success: `(True, list)` - one dict per logical volume, keyed by the field
325          names in `LV_FIELDS`. An empty list means the host has no logical volume.
326        - On failure: `(False, error_message)`.
327
328    Examples
329    --------
330    >>> get_logical_volumes()
331    (True, [{'lv_full_name': 'vg0/root', 'lv_attr': '-wi-ao----', ...}])
332    """
333    return _run(LVS_COMMAND, 'lv', timeout)

Ask LVM for the logical volumes of this host.

Parameters
  • timeout (int, optional): Seconds the command is given. Defaults to 8.
Returns
  • tuple: - On success: (True, list) - one dict per logical volume, keyed by the field names in LV_FIELDS. An empty list means the host has no logical volume.
    • On failure: (False, error_message).
Examples
>>> get_logical_volumes()
(True, [{'lv_full_name': 'vg0/root', 'lv_attr': '-wi-ao----', ...}])
def get_volume_groups(timeout=8):
336def get_volume_groups(timeout=8):
337    """
338    Ask LVM for the volume groups of this host.
339
340    Parameters
341    ----------
342    timeout : int, optional
343        Seconds the command is given. Defaults to 8.
344
345    Returns
346    -------
347    tuple
348        - On success: `(True, list)` - one dict per volume group, keyed by the field
349          names in `VG_FIELDS`. An empty list means the host has no volume group.
350        - On failure: `(False, error_message)`.
351
352    Examples
353    --------
354    >>> get_volume_groups()
355    (True, [{'vg_name': 'vg0', 'vg_size': '107369988096', 'vg_free': '0', ...}])
356    """
357    return _run(VGS_COMMAND, 'vg', timeout)

Ask LVM for the volume groups of this host.

Parameters
  • timeout (int, optional): Seconds the command is given. Defaults to 8.
Returns
  • tuple: - On success: (True, list) - one dict per volume group, keyed by the field names in VG_FIELDS. An empty list means the host has no volume group.
    • On failure: (False, error_message).
Examples
>>> get_volume_groups()
(True, [{'vg_name': 'vg0', 'vg_size': '107369988096', 'vg_free': '0', ...}])
def health(lv):
360def health(lv):
361    """
362    Say what is wrong with a volume, in one clause and without a subject.
363
364    Covers `lv_health_status` and the two states LVM reports beside it: a classic
365    snapshot the kernel threw away, and a snapshot whose merge back into its origin
366    failed. Both leave `lv_health_status` empty.
367
368    Parameters
369    ----------
370    lv : dict
371        One row of `get_logical_volumes()`.
372
373    Returns
374    -------
375    str
376        The clause, or an empty string when nothing is wrong.
377
378    Examples
379    --------
380    >>> health({'lv_health_status': 'out_of_data'})
381    'the pool is out of data space, so every write to a volume in it is queued and then failed'
382    """
383    if is_snapshot_invalid(lv):
384        return 'its copy-on-write store ran full and the kernel threw it away'
385    if lv.get('lv_merge_failed') == 'merge failed':
386        return 'merging it back into its origin failed'
387    if lv.get('lv_check_needed') == 'check needed':
388        return 'the pool is flagged as needing a check before it is used again'
389    status = lv.get('lv_health_status') or ''
390    if not status:
391        return ''
392    # An unknown value is reported rather than swallowed: LVM has added values to this
393    # field before, and a check that only knows the ones it was written against would
394    # report a volume in a state it does not recognise as healthy.
395    return HEALTH_LABELS.get(status, f'LVM reports it as "{status}"')

Say what is wrong with a volume, in one clause and without a subject.

Covers lv_health_status and the two states LVM reports beside it: a classic snapshot the kernel threw away, and a snapshot whose merge back into its origin failed. Both leave lv_health_status empty.

Parameters
Returns
  • str: The clause, or an empty string when nothing is wrong.
Examples
>>> health({'lv_health_status': 'out_of_data'})
'the pool is out of data space, so every write to a volume in it is queued and then failed'
def is_snapshot(lv):
403def is_snapshot(lv):
404    """
405    Tell a snapshot, of either kind, from everything else.
406
407    Parameters
408    ----------
409    lv : dict
410        One row of `get_logical_volumes()`.
411
412    Returns
413    -------
414    bool
415
416    Examples
417    --------
418    >>> is_snapshot({'lv_role': 'public,snapshot,thicksnapshot'})
419    True
420    """
421    return 'snapshot' in _roles(lv)

Tell a snapshot, of either kind, from everything else.

Parameters
Returns
  • bool
Examples
>>> is_snapshot({'lv_role': 'public,snapshot,thicksnapshot'})
True
def is_snapshot_invalid(lv):
424def is_snapshot_invalid(lv):
425    """
426    Tell whether the kernel has thrown a classic snapshot away.
427
428    This is the state a full copy-on-write store ends in. The origin keeps running,
429    the snapshot answers every read with an I/O error, and `lv_health_status` says
430    nothing about it.
431
432    Parameters
433    ----------
434    lv : dict
435        One row of `get_logical_volumes()`.
436
437    Returns
438    -------
439    bool
440
441    Examples
442    --------
443    >>> is_snapshot_invalid({'lv_snapshot_invalid': 'snapshot invalid'})
444    True
445    """
446    return lv.get('lv_snapshot_invalid') == 'snapshot invalid'

Tell whether the kernel has thrown a classic snapshot away.

This is the state a full copy-on-write store ends in. The origin keeps running, the snapshot answers every read with an I/O error, and lv_health_status says nothing about it.

Parameters
Returns
  • bool
Examples
>>> is_snapshot_invalid({'lv_snapshot_invalid': 'snapshot invalid'})
True
def is_thin(lv):
454def is_thin(lv):
455    """
456    Tell a thin volume from a thick one. A thin pool is not a thin volume.
457
458    Parameters
459    ----------
460    lv : dict
461        One row of `get_logical_volumes()`.
462
463    Returns
464    -------
465    bool
466
467    Examples
468    --------
469    >>> is_thin({'lv_layout': 'thin,sparse'})
470    True
471    """
472    layout = _layout(lv)
473    return 'thin' in layout and 'pool' not in layout

Tell a thin volume from a thick one. A thin pool is not a thin volume.

Parameters
Returns
  • bool
Examples
>>> is_thin({'lv_layout': 'thin,sparse'})
True
def is_thin_pool(lv):
476def is_thin_pool(lv):
477    """
478    Tell a thin pool from every other volume.
479
480    Parameters
481    ----------
482    lv : dict
483        One row of `get_logical_volumes()`.
484
485    Returns
486    -------
487    bool
488
489    Examples
490    --------
491    >>> is_thin_pool({'lv_layout': 'thin,pool'})
492    True
493    """
494    layout = _layout(lv)
495    return 'thin' in layout and 'pool' in layout

Tell a thin pool from every other volume.

Parameters
Returns
  • bool
Examples
>>> is_thin_pool({'lv_layout': 'thin,pool'})
True
def metadata_limit(metadata_size):
498def metadata_limit(metadata_size):
499    """
500    Answer at which metadata fill level LVM refuses to create another thin volume or
501    snapshot in a pool.
502
503    LVM keeps back the smaller of 4 MiB and a quarter of the metadata volume, so the
504    limit is 75% for a metadata volume of 16 MiB or less and rises towards 100% for
505    larger ones. A pool that has reached it is fully functional and still cannot take
506    another snapshot, which is why it deserves an answer of its own rather than a flat
507    percentage everywhere.
508
509    Parameters
510    ----------
511    metadata_size : int or str
512        Size of the metadata volume in bytes, as
513        `lv_metadata_size` reports it.
514
515    Returns
516    -------
517    float or None
518        The limit in percent, or None where the size is unknown.
519
520    Examples
521    --------
522    >>> metadata_limit(4 * 1024**2)
523    75.0
524    >>> metadata_limit(64 * 1024**2)
525    93.75
526    """
527    size = to_number(metadata_size)
528    if not size:
529        return None
530    headroom = min(
531        METADATA_HEADROOM_PERCENT,
532        METADATA_HEADROOM_BYTES / size * 100,
533    )
534    return 100 - headroom

Answer at which metadata fill level LVM refuses to create another thin volume or snapshot in a pool.

LVM keeps back the smaller of 4 MiB and a quarter of the metadata volume, so the limit is 75% for a metadata volume of 16 MiB or less and rises towards 100% for larger ones. A pool that has reached it is fully functional and still cannot take another snapshot, which is why it deserves an answer of its own rather than a flat percentage everywhere.

Parameters
  • metadata_size (int or str): Size of the metadata volume in bytes, as lv_metadata_size reports it.
Returns
  • float or None: The limit in percent, or None where the size is unknown.
Examples
>>> metadata_limit(4 * 1024**2)
75.0
>>> metadata_limit(64 * 1024**2)
93.75
def parse_report(stdout, section):
537def parse_report(stdout, section):
538    """
539    Read the rows out of an LVM JSON report.
540
541    Parameters
542    ----------
543    stdout : str
544        What the command printed on stdout.
545    section : str
546        The report section to read, `lv` or `vg`.
547
548    Returns
549    -------
550    tuple
551        - On success: `(True, list)` - one dict per row.
552        - On failure: `(False, error_message)`.
553
554    Examples
555    --------
556    >>> parse_report('{"report": [{"lv": [{"lv_name": "root"}]}]}', 'lv')
557    (True, [{'lv_name': 'root'}])
558    """
559    try:
560        data = json.loads(stdout)
561    except (AttributeError, TypeError, ValueError):
562        return (False, 'Unable to read the LVM report.')
563    # Valid JSON is not yet a report: `null`, a list or a report whose sections are
564    # not lists raised AttributeError or TypeError out of a function that returns a
565    # tuple. Anything but the documented shape is unreadable.
566    if not isinstance(data, dict) or not isinstance(data.get('report') or [], list):
567        return (False, 'Unable to read the LVM report.')
568    rows = []
569    for report in data.get('report') or []:
570        section_rows = report.get(section) if isinstance(report, dict) else None
571        if section_rows is None:
572            continue
573        if not isinstance(section_rows, list):
574            return (False, 'Unable to read the LVM report.')
575        rows.extend(row for row in section_rows if isinstance(row, dict))
576    return (True, rows)

Read the rows out of an LVM JSON report.

Parameters
  • stdout (str): What the command printed on stdout.
  • section (str): The report section to read, lv or vg.
Returns
  • tuple: - On success: (True, list) - one dict per row.
    • On failure: (False, error_message).
Examples
>>> parse_report('{"report": [{"lv": [{"lv_name": "root"}]}]}', 'lv')
(True, [{'lv_name': 'root'}])
def to_number(value):
579def to_number(value):
580    """
581    Read one value of an LVM report as a number.
582
583    LVM leaves a field that does not apply to a volume empty rather than reporting a
584    zero, so an empty percentage means "not measured here" and never "nothing used".
585
586    Parameters
587    ----------
588    value : str
589        The reported value.
590
591    Returns
592    -------
593    float or None
594        The number, or None where the field was empty or not a
595        number.
596
597    Examples
598    --------
599    >>> to_number('74.34')
600    74.34
601    >>> to_number('') is None
602    True
603    """
604    try:
605        return float(value)
606    except (TypeError, ValueError):
607        return None

Read one value of an LVM report as a number.

LVM leaves a field that does not apply to a volume empty rather than reporting a zero, so an empty percentage means "not measured here" and never "nothing used".

Parameters
  • value (str): The reported value.
Returns
  • float or None: The number, or None where the field was empty or not a number.
Examples
>>> to_number('74.34')
74.34
>>> to_number('') is None
True