#!/usr/libexec/isilon/isi_celog_alerting

"""
CELOG Alerting
"""

import json
import time

from isi.app.daemon import daemonize
from isi.celog_lib.periodic import Periodic
from isi.celog_alerting.alert_processor import AlertProcessor
from isi.celog_alerting.full_cluster_check import FullClusterCheck
from isi.celog_alerting.alert_pruner import AlertPruner
from isi.celog_lib.celog_main import keepalive, wait_for_quorum, \
        set_quorum_handler
from isi.celog_alerting.channel_controller import Sender
from isi.celog_lib.log import Log
from isi.celog_lib.config import Config
import isi.celog_alerting.static as static
import isi.celog_alerting.channels as channels

LOG = Log(static.log_prog_name, "Main")
CFG = Config("celog.alert", LOG)

RELOAD = True

def available_channels():
    """Return available channels on this node."""
    avail_chan_list = []
    for chan_def in CFG.get("channels"):
        allowed_lnns = chan_def.get("allowed_lnns", None)
        excluded_lnns = chan_def.get("excluded_lnns", None)

        # If allowed_lnns is set then only those nodes may become master,
        # if it is not set then excluded nodes matters.
        if allowed_lnns:
            if CFG.get("lnn") not in allowed_lnns:
                continue
        elif excluded_lnns:
            if CFG.get("lnn") in excluded_lnns:
                continue

        # If debug_all is set, convert every channel 'type' to debug.
        if CFG.get("debug_all"):
            LOG.info("Setting channel %d as debug channel." % chan_def["id"])
            chan_def["type"] = "debug"

        if channels.channels.has_key(chan_def["type"]):
            if chan_def["enabled"]:
                avail_chan_list.append(chan_def)
        else:
            LOG.error("Channel '%s' specifies undefined channel type '%s'" \
                    % (chan_def["name"], chan_def["type"]))
    return avail_chan_list

def main():
    global RELOAD

    LOG.info("Starting CELOG Alert")
    keepers = []
    periodics = []

    daemon_pidfile='/var/run/isi_celog_alerting.pid'
    daemon_output='/var/log/isi_celog_alerting.log'

    daemonize(pidfilename=daemon_pidfile, stdout=daemon_output,
            stderr=daemon_output, stdin='/dev/null',
            startmsg=None, dopid=True)
    set_quorum_handler()
    wait_for_quorum()
    channels_ident = None

    while True:
        channels_ident_new = json.dumps(CFG.get("channels"))
        if channels_ident != channels_ident_new:
            channels_ident = channels_ident_new

            LOG.info("Loading channels")
            for keeper in keepers:
                keeper.stop()

            for periodic in periodics:
                periodic.stop()

            chan_defs = available_channels()
            keepers = [ AlertProcessor() ]
            periodics = [
                    Periodic(FullClusterCheck(chan_defs, LOG, CFG),
                            CFG.get("clusterfull_interval")),
                    Periodic(AlertPruner(), CFG.get("prune_interval"))
            ]

            for channel in chan_defs:
                periodics.append(Periodic(Sender(channel),
                                          CFG.get("channel_interval")))

            RELOAD = False

        keepalive(keepers, periodics, LOG)
        time.sleep(1)

if __name__ == "__main__":
    main()
