#!/usr/bin/python3
"""
name: pacemonitor.py
description: grab the live Pacemaker XML status and parse it and present
             a type of output for monitoring to parse and create alerts

Copyright 2017 Rackspace

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os
import sys
import time
import signal
import logging
import argparse
import subprocess
import socket
from math import floor
from xml.dom.minidom import parseString
from xml.parsers.expat import ExpatError
# python2 = ConfigParser, python3 = configparser
try:
    import ConfigParser as configparser
except:
    import configparser

__version__ = "1.0.1"


class PaceMonitor(object):
    """PaceMonitor Class - monitor a cluster by parsing it's live XML"""

    def __init__(self, args):
        """Standard initialization"""
        # internal defaults
        self.xmltree = None
        self.xmlconstraints = None
        self.xmlresources = None
        self.debug = False
        self.configfile = '/etc/pacewatcher.conf'
        self.logfile = '/var/log/pacewatcher/pacewatcher.log'
        self.timer = 60
        self.spacereport = 'percent'
        self.spacewarning = 10
        self.spacecritical = 5
        self.initsleep = 30
        self.resourceconfigs = dict()
        self.config_ok = False

        # override via cmdline, cannot change config w/o restart
        if args.configfile:
            self.configfile = args.configfile
        # only during init will cmdline args be respected
        self.init_config(args)
        # we need to set this up now, as the logger needs a static node name
        self.localnode = self.local_node()
        # initialize our logger object
        self.logger = self.init_logger(self.logfile)
        # register a SIGHUP handler
        signal.signal(signal.SIGHUP, self.sighup_handler)
        # respects the DEBUG flag in the object
        self.logger.debug("__init__ complete")

    def set_logformat(self, loghdl):
        """Set/update the log output format"""
        FMT = ('%(asctime)s {} %(name)s: %(levelname)s %(message)s'
               .format(self.localnode))
        logfmt = logging.Formatter(fmt=FMT, datefmt='%b %e %H:%M:%S')
        loghdl.setFormatter(logfmt)

    def init_logger(self, logfile):
        """Logging format: same as syslog
        ex: Feb 01 12:34:56 mynode mydaemon: INFO mymessage
        """
        logger = logging.getLogger('pacemonitor')
        # default is append, another daemon writes to the log - explicit
        loghdl = logging.FileHandler(logfile, 'a')
        self.set_logformat(loghdl)
        logger.addHandler(loghdl)
        if self.debug:
            logger.setLevel(logging.DEBUG)
        else:
            logger.setLevel(logging.INFO)
        return logger

    def update_logger(self):
        """A SIGHUP can change the name of the logfile which is stored
        in the self.logger handler object. We need to remove the handler
        and replace it with a new one, it's an internal list (multiple
        handlers are allowed for one logger object)
        """
        # prep the new handler with a possible new logfile name
        newloghdl = logging.FileHandler(self.logfile, 'a')
        self.set_logformat(newloghdl)
        # safely remove all existing handlers, add the new one
        for hdlr in self.logger.handlers[:]:
            self.logger.removeHandler(hdlr)
        self.logger.addHandler(newloghdl)
        # we got here via HUP, level may have changed in config
        if self.debug:
            self.logger.setLevel(logging.DEBUG)
        else:
            self.logger.setLevel(logging.INFO)
        # Print the running config
        self.print_config()

    def init_config(self, args):
        """Read the config then overwrite with cmdline args"""
        # read in the config, the name is set in __init__
        # - missing config is OK, internal defaults used
        self.read_config(self.configfile)

        # this needs to be writable by 'hacluster'
        if args.logfile:
            self.logfile = args.logfile
        # how long to sleep between checks (seconds)
        if args.timer:
            self.timer = args.timer
        # how long to sleep on initial startup (wait for pacemaker)
        if args.initsleep:
            self.initsleep = args.initsleep
        # report space in percent or amount
        if args.spacereport:
            self.spacereport = args.spacereport
        # threshold for warning level
        if args.spacewarning:
            self.spacewarning = args.spacewarning
        # threshold for critical level
        if args.spacecritical:
            self.spacecritical = args.spacecritical
        # this is for debug logging
        if args.debug:
            self.debug = args.debug

    def read_config(self, configfile):
        """Read in the given configfile"""
        # a missing config is not fatal, internal defaults used
        # note: this can be called by a HUP signal, be careful
        #       and do not try and log, as the logfile could be
        #       changing here
        self.config_ok = True
        try:
            config = configparser.ConfigParser()
            config.read(configfile)

            # global to all daemons
            if config.has_option('pacewatcher', 'logfile'):
                self.logfile = config.get('pacewatcher', 'logfile')

            # unique to this daemon
            if config.has_option('pacemonitor', 'timer'):
                self.timer = config.getint('pacemonitor', 'timer')
            if config.has_option('pacemonitor', 'initsleep'):
                self.initsleep = config.getint('pacemonitor', 'initsleep')
            if config.has_option('pacemonitor', 'spacereport'):
                candidate = config.get('pacemonitor', 'spacereport')
                if candidate in ['percent', 'amount']:
                    self.spacereport = candidate
            # the values of these two will be tested in the method
            if config.has_option('pacemonitor', 'spacewarning'):
                self.spacewarning = config.getint('pacemonitor',
                                                  'spacewarning')
            if config.has_option('pacemonitor', 'spacecritical'):
                self.spacecritical = config.getint('pacemonitor',
                                                   'spacecritical')
            # this is for debug logging
            if config.has_option('pacemonitor', 'debug'):
                self.debug = config.getboolean('pacemonitor', 'debug')

            # treat all unknown sections as resource level configs
            self.resourceconfigs.clear()
            for section in [s for s in config.sections() if s not in
                            ['pacemonitor', 'pacenotify', 'pacewatcher']]:
                rsc_config = dict(config.items(section))
                bad_items = [
                    k for k in rsc_config
                    if (k in ['spacewarning', 'spacecritical'] and
                        not rsc_config[k].isdigit())
                    or (k == 'spacereport' and rsc_config[k] not in
                        ['percent', 'amount'])
                ]
                for item in bad_items:
                    self.config_ok = False
                    del rsc_config[item]
                if rsc_config:
                    self.resourceconfigs[section] = rsc_config
        except:
            self.config_ok = False

    def print_config(self):
        """Print the running config to the log file"""
        if not self.config_ok:
            self.logger.warning("Errors found loading config file")
        self.logger.info("Running config:")
        for item in ['logfile', 'timer', 'initsleep', 'spacereport',
                     'spacewarning', 'spacecritical', 'debug']:
            msg = " - {} = {}".format(item, getattr(self, item))
            self.logger.info(msg)
        for rsc, cfg in self.resourceconfigs.items():
            self.logger.info(" Override: {}".format(rsc))
            for item, val in cfg.items():
                msg = "   - {} = {}".format(item, val)
                self.logger.info(msg)

    def sighup_handler(self, signal, frame):
        """Actions taken when SIGHUP is received"""
        # the HUP might be taking us into and out of DEBUG mode, log as INFO
        self.logger.info("SIGHUP received, re-reading config")
        self.read_config(self.configfile)
        self.update_logger()

    def run_cmd(self, args):
        """Run any given command and return it's output"""
        try:
            p = subprocess.Popen(
                args,
                stdin=None,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                close_fds=True,
                universal_newlines=True
            )
            output, stderror = p.communicate(None)
            retval = p.returncode
        except OSError as e:
            # when p.communicate() fails neither variable is defined
            output = ''
            retval = 1
            if self.debug:
                print(e.strerror)

        return output, retval

    def cluster_xml(self):
        """Return an XML object of the running cluster status"""
        self.logger.debug("Retrieving cluster XML")
        # using the --inactive flag is critical, without it some offline
        # objects (such as clone sets) won't show up in the XML output
        xml, retcode = self.run_cmd(["crm_mon",
                                     "--one-shot",
                                     "--as-xml",
                                     "--inactive"])

        xdoc = None
        if retcode != 0:
            self.logger.critical("Cannot obtain cluster XML")
        else:
            try:
                xdoc = parseString(xml)
            except ExpatError:
                self.logger.critical("Cannot parse cluster XML")
        return xdoc

    def constraint_xml(self):
        """Return an XML object of the constraints status"""
        self.logger.debug("Retrieving constraint XML")
        xml, retcode = self.run_cmd(["cibadmin",
                                     "--scope",
                                     "constraints",
                                     "--query"])

        xdoc = None
        if retcode != 0:
            self.logger.critical("Cannot obtain constraint XML")
        else:
            try:
                xdoc = parseString(xml)
            except ExpatError:
                self.logger.critical("Cannot parse constraint XML")
        return xdoc

    def resource_xml(self):
        """Return an XML object of the resources status"""
        self.logger.debug("Retrieving resource XML")
        xml, retcode = self.run_cmd(["cibadmin",
                                     "--scope",
                                     "resources",
                                     "--query"])

        xdoc = None
        if retcode != 0:
            self.logger.critical("Cannot obtain resource XML")
        else:
            try:
                xdoc = parseString(xml)
            except ExpatError:
                self.logger.critical("Cannot parse resource XML")
        return xdoc

    def local_node(self):
        """Return the cluster local node name of this machine"""
        node, retcode = self.run_cmd(["crm_node", "-n"])

        if retcode != 0:
            # we cannot use self.logger.critical() here as it uses
            # the 'node' variable we're trying to determine
            return "(unknown)"
        else:
            return node.strip()

    def node_online(self, target):
        """Is a given node fully Online or not (capable of clones)"""
        nodes = self.xmltree.getElementsByTagName("nodes")
        if nodes.length > 0:
            # <nodes>
            #   <node name="name">
            for node in nodes[0].getElementsByTagName("node"):
                if node.getAttribute("name") == target:
                    # online/offline is a bool but standby/maintenance are
                    # sub-attributes of online=true
                    if node.getAttribute("online") == "true":
                        if (
                            node.getAttribute("standby") == "true" or
                            node.getAttribute("maintenance") == "true"
                           ):
                            return False
                        else:
                            return True
                    else:
                        # online != true
                        return False
            # node was not in nodelist?
            return False
        else:
            # node was not found in cluster?
            return False

    def _rsrc_opval(self, rsrc, opname, opkey):
        """Given a resource, return it's value for the named Operation"""
        self.logger.debug('Checking resource {} op {} key {}'.format(
                          rsrc, opname, opkey))
        # <resources>
        #   <primitive id="rsrc">
        #     <operations>
        #       <op name="opname" opkey="foobar">
        for primitive in self.xmlresources.getElementsByTagName("primitive"):
            if primitive.getAttribute("id") == rsrc:
                for op in primitive.getElementsByTagName("op"):
                    if op.getAttribute("name") == opname:
                        opval = op.getAttribute(opkey)
                        self.logger.debug('Resource {} op {} key {} value {}'.
                                          format(rsrc, opname, opkey, opval))
                        return opval
        # No op found
        return ""

    def status_nodes(self):
        """Report the status of all nodes in the cluster"""
        self.logger.debug("Checking node status")
        nodes = self.xmltree.getElementsByTagName("nodes")
        if nodes.length > 0:
            # <nodes>
            #   <node name="name">
            for node in nodes[0].getElementsByTagName("node"):
                addr = None
                try:
                    addr = socket.gethostbyname(node.getAttribute("name"))
                except Exception:
                    pass
                if not addr:
                    msg = 'node name {} does not resolve to an IP'.format(
                        node.getAttribute('name'))
                    self.logger.warning(msg)
                else:
                    msg = 'node {} resolves to {}'.format(
                        node.getAttribute('name'), addr)
                    self.logger.info(msg)
                # online/offline is a bool but standby/maintenance are
                # sub-attributes of online=true
                if node.getAttribute("online") == "true":
                    if node.getAttribute("standby") == "true":
                        msg = 'node {} in Standby mode'.format(
                              node.getAttribute("name"))
                        self.logger.warning(msg)
                    elif node.getAttribute("maintenance") == "true":
                        msg = 'node {} in Maintenance mode'.format(
                              node.getAttribute("name"))
                        self.logger.warning(msg)
                    else:
                        msg = 'node {} in Online mode'.format(
                              node.getAttribute("name"))
                        self.logger.info(msg)
                else:
                    msg = 'node {} is Offline'.format(
                          node.getAttribute("name"))
                    self.logger.critical(msg)

    def status_stonith(self):
        """Report the status of all stonith objects in the cluster"""
        self.logger.debug("Checking stonith status")
        resources = self.xmltree.getElementsByTagName("resources")
        if resources.length > 0:
            # <resources>
            #   <resource id="name of fence device" resource_agent="fencer">
            #     <node name="name of node running it">
            for resource in resources[0].getElementsByTagName("resource"):
                if (
                    resource.parentNode.nodeName == 'resources' and
                    "stonith:" in resource.getAttribute("resource_agent")
                   ):
                    nodes = resource.getElementsByTagName("node")
                    if nodes.length > 0:
                        for node in nodes:
                            msg = 'stonith {} is {} on {}'.format(
                                  resource.getAttribute("id"),
                                  resource.getAttribute("role"),
                                  node.getAttribute("name"))
                            if resource.getAttribute("role") != "Started":
                                self.logger.critical(msg)
                            else:
                                self.logger.info(msg)
                    else:
                        msg = 'stonith {} is {}'.format(
                              resource.getAttribute("id"),
                              resource.getAttribute("role"))
                        self.logger.critical(msg)

    def status_clones(self):
        """Report the status of all clones in the cluster"""
        self.logger.debug("Checking clone status")
        clones = self.xmltree.getElementsByTagName("clone")
        if clones.length > 0:
            # <resources>
            #   <clone id="name">
            #     <resource id="name">
            #       <node name="nam">
            for clone in clones:
                # when a clone set is stopped, multiple XML elements
                # exist but without nodes owning them, so the logging
                # looks identical. We'll add a counter to the message.
                nodecounter = 1
                for resource in clone.getElementsByTagName("resource"):
                    nodes = resource.getElementsByTagName("node")
                    if nodes.length > 0:
                        for node in nodes:
                            msg = 'clone {} is {} on {}'.format(
                                  resource.parentNode.getAttribute("id"),
                                  resource.getAttribute("role"),
                                  node.getAttribute("name"))
                            self.logger.info(msg)
                    else:
                        # lack of node elements means it's not role=Started
                        msg = 'clone {} is {} (node {})'.format(
                              resource.parentNode.getAttribute("id"),
                              resource.getAttribute("role"),
                              str(nodecounter))
                        self.logger.critical(msg)
                        # prepare for the next unknown node in the clone set
                        nodecounter += 1

    def status_ungrouped(self):
        """Report the status of all ungrouped resources in the cluster"""
        self.logger.debug("Checking ungrouped resources status")
        resources = self.xmltree.getElementsByTagName("resources")
        # <resources>
        #   <resource id="name">
        #     <node name="name of node running it">
        if resources.length > 0:
            # Like clones, an offline resource has no known node
            nodecounter = 1
            for resource in resources[0].getElementsByTagName("resource"):
                if (
                    resource.parentNode.nodeName == 'resources' and
                    "stonith:" not in resource.getAttribute("resource_agent")
                   ):
                    rscid = resource.getAttribute("id")
                    rscop = self._rsrc_opval(rscid, 'monitor', 'on-fail')
                    nodes = resource.getElementsByTagName("node")
                    if nodes.length > 0:
                        for node in nodes:
                            msg = 'resource {} is {} on {}'.format(
                                  rscid,
                                  resource.getAttribute("role"),
                                  node.getAttribute("name"))
                            self.logger.info(msg)
                    else:
                        # lack of node elements means it's not role=Started
                        msg = 'resource {} is {} (node {})'.format(
                              rscid,
                              resource.getAttribute("role"),
                              str(nodecounter))
                        if rscop != 'ignore':
                            self.logger.critical(msg)
                        else:
                            self.logger.warning(msg)
                        # prepare for the next unknown node
                        nodecounter += 1

    def status_groups(self):
        """Report the status of all grouped resources in the cluster"""
        self.logger.debug("Checking grouped resources status")
        groups = self.xmltree.getElementsByTagName("group")
        if groups.length > 0:
            # <resources>
            #   <group id="name">
            #     <resource id="name">
            #       <node name="name">
            for group in groups:
                for resource in group.getElementsByTagName("resource"):
                    rscid = resource.getAttribute("id")
                    rscop = self._rsrc_opval(rscid, 'monitor', 'on-fail')
                    nodes = resource.getElementsByTagName("node")
                    if nodes.length > 0:
                        for node in nodes:
                            msg = 'group {} resource {} is {} on {}'.format(
                                  group.getAttribute("id"),
                                  rscid,
                                  resource.getAttribute("role"),
                                  node.getAttribute("name"))
                            self.logger.info(msg)
                    else:
                        # lack of node elements means it's not role=Started
                        msg = 'group {} resouce {} is {}'.format(
                              rscid,
                              resource.getAttribute("id"),
                              resource.getAttribute("role"))
                        if rscop != 'ignore':
                            self.logger.critical(msg)
                        else:
                            self.logger.warning(msg)

    def status_constraints(self):
        """Report the status of all unexpected constraints in the cluster"""
        self.logger.debug("Checking constraint status")
        constraints = self.xmlconstraints.getElementsByTagName("constraints")
        if constraints.length > 0:
            # <constraints>
            #   <rsc_order id="name">
            #   <rsc_location id="name">
            #     <rule id="name" score="INFINITY">
            #       <expression id="name">
            #       <date_expression id="name">
            for constraint in constraints:
                locations = constraint.getElementsByTagName("rsc_location")
                if locations.length > 0:
                    for loc in locations:
                        if (
                            loc.getAttribute("id").startswith("cli-ban") or
                            loc.getAttribute("id").startswith("cli-prefer")
                           ):
                            msg = ('location constraint {} type {} '
                                   'is {}').format(
                                   loc.getAttribute("id"),
                                   loc.getAttribute("rsc"),
                                   loc.getAttribute("role"))
                            self.logger.warning(msg)

    def status_filesystems(self):
        """Report the status of all local shared filesystems in the cluster"""
        """This requires three pieces of data to correlate"""
        self.logger.debug("Checking filesystems status")
        # crm_mon --as-cml --one-shot
        resources = self.xmltree.getElementsByTagName("resource")
        # <resources>
        #   <resource id="name in cluster" ...>
        #     <node name="node running it">
        if resources.length > 0:
            for resource in resources:
                if (
                    (
                     resource.getAttribute("resource_agent") ==
                     "ocf::heartbeat:Filesystem"
                    ) and
                    resource.getAttribute("role") == "Started" and
                    resource.getAttribute("active") == "true" and
                    resource.getAttribute("managed") == "true" and
                    int(resource.getAttribute("nodes_running_on")) > 0
                   ):
                    resname = resource.getAttribute("id")
                    nodes = resource.getElementsByTagName("node")
                    if nodes.length > 0:
                        # needed logic nest is too deep for flake8 here
                        self._fs_nodecheck(nodes, resname)

    def _fs_nodecheck(self, nodes, resname):
        """Internal function to report disk space if mounted on this node"""
        # flake8 line length compliance made this a second method
        # instead of combining it with status_filesystems()
        for node in nodes:
            if node.getAttribute("name") == self.localnode:
                # cibadmin --scope=resources --query
                primitives = self.xmlresources.getElementsByTagName(
                    "primitive"
                )
                # <primitive id="name">
                #   <instance_attributes id="name-instance-attributes>
                #     <nvpair id="name-instance_attributes-directory">
                if primitives.length > 0:
                    for primitive in primitives:
                        if primitive.getAttribute("id") == resname:
                            nvpairs = primitive.getElementsByTagName("nvpair")
                            if not nvpairs.length > 0:
                                continue
                            for nvpair in nvpairs:
                                srch = (
                                    '{}-instance_attributes-directory'
                                    .format(resname)
                                )
                                if nvpair.getAttribute("id") == srch:
                                    fsmount = nvpair.getAttribute("value")
                                    if not fsmount:
                                        continue
                                    self.report_fs(
                                        resname,
                                        fsmount,
                                        node.getAttribute("name")
                                    )

    def get_rsc_config(self, resource, item):
        """Returns the specific or global level config value for a resource"""
        default = getattr(self, item)
        return self.resourceconfigs.get(resource, {}).get(item, default)

    def report_fs(self, resname, fsmount, nodename):
        """Report on a filesystem give it's mount"""
        # mode = percent, threshold 1 < N <100
        # mode = amount, threshold 1 < N < (total space)
        # internal default: setting a threshold to 0 == disable
        if os.path.ismount(fsmount):
            fst = os.statvfs(fsmount)

            # b_bavail = unpriv, b_bfree = root. 80% use case is a service
            # not running as root (mariadb, etc.) so report unpriv
            btotal = fst.f_blocks*fst.f_frsize
            bfree = fst.f_bavail*fst.f_frsize
            bused = (fst.f_blocks-fst.f_bavail)*fst.f_frsize

            # set up the message to log, always the same
            htotal = self.human_fs(btotal)
            hfree = self.human_fs(bfree)
            hused = self.human_fs(bused)
            msg = ('resource {} filesystem {} mounted on {} '
                   '[ {} total | {} used | {} free ]').format(
                   resname, fsmount, nodename, htotal, hused, hfree)

            # Determine critical & warning thresholds
            # Initialize to zero so we don't alert on invalid config values
            tcrit = 0
            twarn = 0
            spacereport = self.get_rsc_config(resname, 'spacereport')
            spacecritical = int(self.get_rsc_config(resname, 'spacecritical'))
            spacewarning = int(self.get_rsc_config(resname, 'spacewarning'))
            if spacereport == 'percent':
                # percentage free threshold calculations, floats required
                if spacecritical in range(1, 100):
                    tcrit = int(floor(float(btotal)*spacecritical/100))
                if spacewarning in range(1, 100):
                    twarn = int(floor(float(btotal)*spacewarning/100))
            elif spacereport == 'amount':
                # amount threshold, ex: 46269612032 -> 44126 GB
                if spacecritical > 0:
                    tcrit = spacecritical*1024*1024
                if self.spacewarning > 0:
                    twarn = spacewarning*1024*1024

            # Check if free space is below either threshold
            if bfree < tcrit:
                self.logger.critical(msg)
            elif bfree < twarn:
                self.logger.warning(msg)
            else:
                # default
                self.logger.info(msg)

    def human_fs(self, rawbytes):
        """Convert bytes to a human readable (string) output
        Match 'df -h' style output, but add float() precision
        https://www.gnu.org/software/coreutils/manual/html_node/Block-size.html
        """

        # suffixes are listed left -> right in increasing order
        suffixes = "KMGTPEZY"
        base = 1024
        floatbytes = float(rawbytes)

        # handle the easy (<1024) case, return the bytes
        if floatbytes < base:
            return '{}B'.format(floatbytes)

        # anything >= 1024 (base unit)
        for iterator, suffix in enumerate(suffixes):
            # work our way up the suffixes
            unit = base ** (iterator + 2)
            if floatbytes < unit:
                return '{:.1f}{}'.format(
                       (base * floatbytes / unit),
                       suffix)
        # if we somehow get here, return a safe string
        # https://en.wikipedia.org/wiki/NaN
        return "NaN"

    def check_nodename(self):
        """Check that the local node name hasn't changed
        Updates the log formatter (which relies on the node name)
        if it has changed, and store the new name
        """
        nodename = self.local_node()
        if self.localnode != nodename:
            self.localnode = nodename
            for hdlr in self.logger.handlers[:]:
                self.set_logformat(hdlr)

    def run(self):
        """Main entry point/message pump"""
        # the systemd unit starts us right after pacemaker, we need to
        # sleep for a bit to allow pacemaker to finish booting up and
        # bringing all expected services online
        msg = ('Version {} starting up, sleeping {} seconds waiting for '
               'Pacemaker to initialize').format(__version__, self.initsleep)
        self.logger.info(msg)
        # Print the running config
        self.print_config()
        time.sleep(self.initsleep)

        while True:
            try:
                # If the local node name reported by 'crm_node -n' changes for
                # any reason, it prevents certain functions (e.g. disk space
                # reporting) to fail - so we need to check & update the node
                # name in that case.
                # This can definitely occur if the cluster wasn't running
                # properly when we started and the node names are different
                # to the result of 'uname -n' (which is the default value
                # reported by 'crm_node -n' if the cluster is down)
                self.check_nodename()

                # Populate all class XML objects with the lastest data
                self.xmltree = self.cluster_xml()
                self.xmlconstraints = self.constraint_xml()
                self.xmlresources = self.resource_xml()

                # Some checks require both XML documents
                if self.xmltree and self.xmlresources:
                    self.status_nodes()
                    self.status_stonith()
                    self.status_clones()
                    self.status_ungrouped()
                    self.status_groups()
                    self.status_filesystems()

                # Only the constraint XML document is needed
                if self.xmlconstraints:
                    self.status_constraints()

            except Exception as e:
                print(e)
            time.sleep(self.timer)


def parse_args():
    """Argument parsing routine"""
    parser = argparse.ArgumentParser(description='PaceMonitor')
    parser.add_argument('--version',
                        action='version',
                        version=__version__,
                        help='Display the version')
    parser.add_argument('-c',
                        '--configfile',
                        required=False,
                        dest='configfile',
                        help='Configuration file to read')
    parser.add_argument('-l',
                        '--logfile',
                        required=False,
                        dest='logfile',
                        help='Name of logfile to write')
    parser.add_argument('-t',
                        '--timer',
                        required=False,
                        type=int,
                        dest='timer',
                        help='Time to sleep between checks in seconds')
    parser.add_argument('-i',
                        '--initsleep',
                        required=False,
                        type=int,
                        dest='initsleep',
                        help='Time to sleep on first start in seconds')
    parser.add_argument('-r',
                        '--spacereport',
                        required=False,
                        dest='spacereport',
                        choices=['percent', 'amount'],
                        help='Report disk space in percent or amount')
    parser.add_argument('-w',
                        '--spacewarning',
                        required=False,
                        dest='spacewarning',
                        type=int,
                        help='Warning threshold for low disk space')
    parser.add_argument('-e',
                        '--spacecritical',
                        required=False,
                        dest='spacecritical',
                        type=int,
                        help='Critical threshold for low disk space')
    parser.add_argument('-d',
                        '--debug',
                        action='store_true',
                        required=False,
                        dest='debug',
                        help='Log messages with DEBUG level or higher')
    return parser.parse_args()


def sigbye_handler(signal, frame):
    """Exit function triggered by caught signals"""
    sys.exit(0)


if __name__ == '__main__':
    """Main entry point for PaceMonitor"""
    # register a clean shutdown for the usual signals
    signal.signal(signal.SIGINT, sigbye_handler)
    signal.signal(signal.SIGQUIT, sigbye_handler)
    signal.signal(signal.SIGTERM, sigbye_handler)

    # parse any cmdline arguments
    args = parse_args()

    # main routine, it sleeps internally
    try:
        monitor = PaceMonitor(args)
        if monitor:
            monitor.run()
    except Exception as e:
        print(e)
        sys.exit(1)
