#!/usr/bin/python3
#
# Univention Nagios Plugin
#  check slapd's/udl's mdb maxsize
#
# Like what you see? Join us!
# https://www.univention.com/about-us/careers/vacancies/
#
# Copyright 2007-2024 Univention GmbH
#
# https://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <https://www.gnu.org/licenses/>.

import argparse
import os
import subprocess
import sys

from univention.config_registry import ConfigRegistry


STATE_OK = 0
STATE_WARNING = 1
STATE_CRITICAL = 2

parser = argparse.ArgumentParser()
parser.add_argument('-w', '--warn', type=int, default=75)
parser.add_argument('-c', '--critical', type=int, default=90)
parser.add_argument('-l', '--listener-only', action='store_true')
args = parser.parse_args()

ucr = ConfigRegistry()
ucr.load()

service_prefix = 'LISTENER' if args.listener_only else 'SLAPD'
service = 'univention-directory-listener' if args.listener_only else 'slapd'
ucr_variable = 'listener/cache/mdb/maxsize' if args.listener_only else 'ldap/database/mdb/maxsize'


def nagios_exit(state, msg):
    print('%s %s: %s' % (service_prefix, {STATE_OK: 'MDB OK', STATE_WARNING: 'MDB WARNING', STATE_CRITICAL: 'MDB CRITICAL'}.get(state, 'MDB UNKNOWN'), msg))
    sys.exit(state)


files = []
if args.listener_only:
    files.append('/var/lib/univention-directory-listener/cache')
else:
    if ucr.get('ldap/database/type') == 'mdb':
        files.append('/var/lib/univention-ldap/ldap')
    if sys.maxsize > 2 ** 32:
        files.append('/var/lib/univention-ldap/translog')

files = [file_ for file_ in files if os.path.exists('%s/data.mdb' % (file_))]

if not files:
    nagios_exit(STATE_OK, 'OpenLDAP backend is not mdb')

if not os.path.exists('/usr/bin/mdb_stat'):
    nagios_exit(STATE_WARNING, 'mdb_stat not found, please install lmdb-utils')

errors = []
warnings = []
success = []
for mdb_dir in files:
    try:
        output = subprocess.check_output(['/usr/bin/mdb_stat', '-ef', mdb_dir], close_fds=True, env={'LC_ALL': 'C'})
    except subprocess.CalledProcessError:
        nagios_exit(STATE_CRITICAL, 'mdb_stat -ef %s failed' % (mdb_dir,))
    output = output.decode("utf-8", "replace")
    stat = dict(line.strip().lower().split(': ', 1) for line in output.splitlines() if ': ' in line)
    try:
        free_pages = int(stat['free pages'])
        in_use_vs_untouched_pages = round((int(stat['number of pages used']) - free_pages) * 100 / (int(stat['max pages']) - free_pages), 2)
    except KeyError:  # API change in the future
        nagios_exit(STATE_CRITICAL, 'output of "mdb_stat -e %s" could not be parsed: %s' % (mdb_dir, output))

    if in_use_vs_untouched_pages >= args.critical:
        errors.append("More than %s%% (in fact %s%%) of mdb database %s pages are used, please increase %s (and restart %s)" % (args.critical, in_use_vs_untouched_pages, mdb_dir, ucr_variable, service))
    elif in_use_vs_untouched_pages >= args.warn:
        warnings.append("More than %s%% (in fact %s%%) of mdb database %s pages are used, consider increasing %s (and restart %s)" % (args.warn, in_use_vs_untouched_pages, mdb_dir, ucr_variable, service))
    else:
        success.append("Database %s operational (in fact %s%% mdb pages used)" % (mdb_dir, in_use_vs_untouched_pages))
result = STATE_CRITICAL if errors else (STATE_WARNING if warnings else STATE_OK)
nagios_exit(result, '\n'.join(errors + warnings + success))
