#!/usr/bin/python3
#
# Univention Monitoring Plugin
#  check_univention_ad_connector: check Active Directory connector status
#
# Like what you see? Join us!
# https://www.univention.com/about-us/careers/vacancies/
#
# Copyright 2011-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 re
import subprocess

from univention.config_registry import ucr
from univention.monitoring import Alert


RE_REJECT = re.compile(r'^ *[1-9]+: *(AD|UCS) DN:.*')


class ADConnector(Alert):

    def write_metrics(self):
        connectors = ('connector %s' % ucr.get('connector/listener/additionalbasenames', '')).split(' ')
        for connector in connectors:
            if not connector:
                continue
            self.write_connector_metrics(len(connectors), connector)

    def write_connector_metrics(self, connectors, connector):
        # check whether we can connect to the AD
        # CRITICAL: in case we cannot connect to the AD
        rc = self.exec_command(['univention-adsearch', '-c', connector, 'cn=users'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)[0]
        self.write_metric('univention_ad_connector_ad_reachable', 1 if rc == 0 else 0, connector=connector)

        # check whether the AD connector is running; for this, get the exact command
        # that was used to launch the process; remove multiple whitespaces and quotes
        # in order to match the command via check_procs
        # WARNING: if not exactly the number of configured connectors is running
        # CRITICAL: if no process is running
        rc, output = self.exec_command(['/usr/lib/nagios/plugins/check_procs', '-w', '%d:%d' % (connectors, connectors), '-c', '1:', '--ereg-argument-array', '^([^ ]+)?python.*univention.connector.ad.main(.py)?'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        if rc == 1:
            rc2, output = self.exec_command(['/usr/lib/nagios/plugins/check_procs', '-w', '%d' % (connectors,), '-c', '1:', '--ereg-argument-array', '^([^ ]+)?python.*univention.connector.ad.main(.py)?'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            output = {
                1: 'More than the %s configured AD connectors are running!' % (connectors,),
                2: 'Less than the %s configured AD connectors are running!' % (connectors,),
            }.get(rc2, 'Unknown state!')
        elif rc == 2:
            output = 'No AD connector is running!'
        else:
            output = 'Unknown state!'
        self.log.debug(output)
        self.write_metric('univention_ad_connector_running', rc if rc in (0, 1, 2) else -1, connector=connector)

        # count rejects by parsing the output of univention-adconnector-list-rejected
        # WARNING: if there are any rejects
        rc, output = self.exec_command(['univention-adconnector-list-rejected', '-c', connector])
        rejects = sum(1 for line in output.splitlines() if RE_REJECT.match(line))

        self.write_metric('univention_ad_connector_rejects', rejects, connector=connector)
        if rejects:
            self.log.debug('Found %d reject(s)! Please check output of univention-adconnector-list-rejected.' % (rejects,))


if __name__ == '__main__':
    ADConnector.main()
