#!/usr/lib64/linuxfabrik-monitoring-plugins/venv/bin/python
# -*- coding: utf-8; py-indent-offset: 4 -*-
#
# Author:  Linuxfabrik GmbH, Zurich, Switzerland
# Contact: info (at) linuxfabrik (dot) ch
#          https://www.linuxfabrik.ch/
# License: The Unlicense, see LICENSE file.

# https://github.com/Linuxfabrik/monitoring-plugins/blob/main/CONTRIBUTING.md

"""See the check's README for more details."""

import argparse
import re
import sys

import lib.args
import lib.base
import lib.human
import lib.lftest
import lib.shell
import lib.txt
from lib.globals import STATE_UNKNOWN, STATE_WARN

__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2026102403'

DESCRIPTION = """Checks the current disk usage of all systemd journal files (archived and active
combined). Alerts when journal disk usage exceeds the configured thresholds.
Requires root or sudo."""

DEFAULT_WARN = '6'  # GiB; journald: "capped to 4G" per default
SYSTEMD_DEFAULT_MAX_USE = '4G'
SYSTEMD_DEFAULT_KEEP_FREE = '1M'


def parse_args():
    """Parse command line arguments using argparse."""
    parser = argparse.ArgumentParser(
        description=DESCRIPTION,
        epilog=lib.args.epilog(__file__),
        formatter_class=lib.args.HelpFormatter,
    )

    parser.add_argument(
        '-V',
        '--version',
        action='version',
        version=f'%(prog)s: v{__version__} by {__author__}',
    )

    parser.add_argument(
        '--always-ok',
        help=lib.args.help('--always-ok'),
        dest='ALWAYS_OK',
        action='store_true',
        default=False,
    )

    parser.add_argument(
        '--no-perfdata',
        help=lib.args.help('--no-perfdata'),
        dest='NO_PERFDATA',
        action='store_true',
        default=False,
    )

    parser.add_argument(
        '--test',
        help=lib.args.help('--test'),
        dest='TEST',
        type=lib.args.csv,
    )

    parser.add_argument(
        '-w',
        '--warning',
        help='WARN threshold for the journal disk usage in GiB. '
        'Supports Nagios ranges. '
        'Example: `--warning=10` alerts above 10 GiB. '
        'Default: %(default)s',
        dest='WARN',
        default=DEFAULT_WARN,
    )

    args, _ = parser.parse_known_args()
    return args


def extract_config(output):
    """
    Extracts the last occurrences of SystemMaxUse and SystemKeepFree.
    Returns a tuple: (SystemMaxUse_value, SystemKeepFree_value).
    """
    max_use = None
    keep_free = None
    for line in reversed(output.splitlines()):
        if max_use is None and line.startswith('SystemMaxUse='):
            max_use = line.split('=', 1)[1].strip()
        if keep_free is None and line.startswith('SystemKeepFree='):
            keep_free = line.split('=', 1)[1].strip()
        if max_use is not None and keep_free is not None:
            break
    if max_use is None:
        max_use = SYSTEMD_DEFAULT_MAX_USE
    if keep_free is None:
        keep_free = SYSTEMD_DEFAULT_KEEP_FREE
    return max_use, keep_free


def main():
    """The main function. This is where the magic happens."""

    # parse the command line
    try:
        args = parse_args()
    except SystemExit:
        sys.exit(STATE_UNKNOWN)

    # fetch data
    cmd = ['journalctl', '--disk-usage']
    if args.TEST is None:
        stdout, stderr, retc = lib.base.coe(lib.shell.shell_exec(cmd))
    else:
        # do not call the command, put in test data
        stdout, stderr, retc = lib.lftest.test(args.TEST)
    if retc != 0:
        # journalctl ends with this when the account may not read a single journal
        # file (src/shared/journal-util.c)
        if 'insufficient permissions' in stderr:
            lib.base.cu(
                'Not allowed to read the systemd journal. Run this plugin as root or '
                'via sudo, or add the account running it to the `systemd-journal` '
                'group.'
            )
        # a journal that cannot be measured says nothing about how full it is
        lib.base.cu(f'`{" ".join(cmd)}` failed (exit {retc}): {stderr.strip()}')

    # journalctl exits 0 and only adds a hint on stderr when the account may read some
    # journal files but not all of them, typically its own user journal but not the
    # system journal (src/shared/journal-util.c). The answer would then cover a fraction
    # of the journal while looking like the whole. Verified against systemd 247, 252
    # and 257 on Debian 11, 12 and 13.
    if 'You are currently not seeing messages from' in stderr:
        lib.base.cu(
            'Not allowed to read the whole systemd journal, only the part that belongs '
            'to the account running this plugin. Run this plugin as root or via sudo, '
            'or add the account running it to the `systemd-journal` group.'
        )

    if args.TEST is None:
        # get journald's thresholds
        cmd = ['systemd-analyze', 'cat-config', 'systemd/journald.conf']
        config, stderr, retc = lib.base.coe(lib.shell.shell_exec(cmd))
        if retc != 0:
            lib.base.cu(f'`{" ".join(cmd)}` failed (exit {retc}): {stderr.strip()}')
        max_use, keep_free = extract_config(config)
    else:
        max_use, keep_free = SYSTEMD_DEFAULT_MAX_USE, SYSTEMD_DEFAULT_KEEP_FREE

    # init some vars
    msg = ''
    perfdata = ''

    # possible values of stdout according to systemd journalctl.c source code history:
    #   Archived and active journals take up %s on disk.\n
    #   Archived and active journals take up %s in the file system.\n
    #   Journals take up %s on disk.\n
    value = lib.txt.extract_str(
        stdout, ' take up ', ' ', include_fromto=False, be_tolerant=False
    )
    # journalctl prints the size with format_bytes() (src/basic/format-util.c in the
    # systemd source): an integer or one decimal, an IEC suffix from K to E, and a
    # trailing B below 1K. Anything else would end up as 0 bytes, which reads as an
    # empty journal.
    if not re.fullmatch(r'\d+(\.\d+)?[KMGTPE]?B?', value):
        lib.base.cu(
            f'Unable to read the journal disk usage from `{" ".join(cmd)}`: '
            f'"{stdout.strip()}"'
        )
    value = lib.human.human2bytes(value)

    # analyze data
    # every bound of the range is a number of GiB
    warn = lib.human.humanrange2bytes(re.sub(r'(\d+(?:\.\d+)?)', r'\1GiB', args.WARN))
    state = lib.base.get_state(value, warn, None, _operator='range')

    # build the message
    msg += (
        f'{lib.human.bytes2human(value)} used{lib.base.state2str(state, prefix=" ")} '
        '(sum of all archived and active journal files; '
        f'SystemMaxUse={max_use} SystemKeepFree={keep_free})'
    )
    if state == STATE_WARN:
        msg += (
            '. Configure `SystemMaxUse` and `SystemKeepFree` in '
            '`/etc/systemd/journald.conf` or a drop-in below '
            '`/etc/systemd/journald.conf.d/`, '
            'or remove the oldest archived journal files with '
            '`sudo journalctl --vacuum-size=...`, `--vacuum-time=...` and/or '
            '`--vacuum-files=...`.'
        )
    perfdata += lib.base.get_perfdata(
        'journald-usage',
        value,
        uom='B',
        warn=warn,
        crit=None,
        _min=0,
        _max=None,
    )

    # over and out
    lib.base.oao(
        msg, state, perfdata, always_ok=args.ALWAYS_OK, no_perfdata=args.NO_PERFDATA
    )


if __name__ == '__main__':
    try:
        main()
    except Exception:
        lib.base.cu()
