# Path: overc/src/init.py
# def init_db_engine(connect):
#     """ Init Sqlalchemy engine
#     :param connect: Database connection string
#     :type connect: str
#     :rtype: sqlalchemy.engine.Engine
#     """
#     return create_engine(connect, convert_unicode=True)
# 
# def init_db_session(engine):
#     """ Init DB session
#     :param engine: Engine
#     :type engine: sqlalchemy.engine.Engine
#     :rtype: sqlalchemy.orm.scoped_session
#     """
#     Session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
# 
#     # Models
#     from overc.lib.db.models import Base
#     Base.query = Session.query_property()
#     Base.metadata.create_all(bind=engine)  # TODO: remove automatic table creation
# 
#     return Session
# 
# Path: overc/lib/db/models.py
# class Server(Base):
# class Service(Base):
# class state_t(int):
# class ServiceState(Base):
# class Alert(Base):
#     def __str__(self):
#     def __unicode__(self):
#     def update_timed_out(self):
#     def __str__(self):
#     def __unicode__(self):
#     def __new__(cls, state):
#     def is_valid(cls, state):
#     def prev(self):
#     def __unicode__(self):
#     def severity(self):
#     OK = 0
#     WARN = 1
#     FAIL = 2
#     UNK = 3
# 
# Path: overc/lib/alerts.py
# class AlertPlugin(object):
#     def __init__(self, name, cwd, command):
#     def send(self, message):
# def send_alert_with_plugins(alert_plugins, message):


import logging
import os, tempfile
import signal, errno
import fcntl
from time import sleep
from overc.src.init import init_db_engine, init_db_session
from overc.lib.db import models
from overc.lib import alerts
from contextlib import contextmanager
    # Finish
    ssn.commit()
    return new_alerts


def _send_pending_alerts(ssn, alert_plugins):
    """ Send pending alerts
    :param ssn: Database session
    :type ssn: sqlalchemy.orm.session.Session
    :param alert_plugins: Application config for alerts
    :type alert_plugins: list[alerts.AlertPlugin]
    :returns: The number of alerts sent
    :rtype: int
    """
    # Fetch all alerts which were not reported
    pending_alerts = ssn.query(models.Alert)\
        .filter(models.Alert.reported == False)\
        .all()

    # Report them one by one
    for a in pending_alerts:
        logger.debug(u'Sending alert #{id}: server={server}, service={service}, [{channel}/{event}]'.format(id=a.id, server=a.server, service=a.service, channel=a.channel, event=a.event))

        # Prepare alert message
        alert_message = unicode(a) + "\n"
        if a.service and a.service.state:
            s = a.service.state
            alert_message += u"Current: {}: {}\n".format(s.state, s.info)

        # Potential exceptions are handled & logged down there

# Path: overc/src/init.py
# def init_db_engine(connect):
#     """ Init Sqlalchemy engine
#     :param connect: Database connection string
#     :type connect: str
#     :rtype: sqlalchemy.engine.Engine
#     """
#     return create_engine(connect, convert_unicode=True)
# 
# def init_db_session(engine):
#     """ Init DB session
#     :param engine: Engine
#     :type engine: sqlalchemy.engine.Engine
#     :rtype: sqlalchemy.orm.scoped_session
#     """
#     Session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
# 
#     # Models
#     from overc.lib.db.models import Base
#     Base.query = Session.query_property()
#     Base.metadata.create_all(bind=engine)  # TODO: remove automatic table creation
# 
#     return Session
# 
# Path: overc/lib/db/models.py
# class Server(Base):
# class Service(Base):
# class state_t(int):
# class ServiceState(Base):
# class Alert(Base):
#     def __str__(self):
#     def __unicode__(self):
#     def update_timed_out(self):
#     def __str__(self):
#     def __unicode__(self):
#     def __new__(cls, state):
#     def is_valid(cls, state):
#     def prev(self):
#     def __unicode__(self):
#     def severity(self):
#     OK = 0
#     WARN = 1
#     FAIL = 2
#     UNK = 3
# 
# Path: overc/lib/alerts.py
# class AlertPlugin(object):
#     def __init__(self, name, cwd, command):
#     def send(self, message):
# def send_alert_with_plugins(alert_plugins, message):


# Path: overc/lib/supervise.py
import logging
import os, tempfile
import signal, errno
import fcntl
from time import sleep
from overc.src.init import init_db_engine, init_db_session
from overc.lib.db import models
from overc.lib import alerts
from contextlib import contextmanager

    # Finish
    ssn.commit()
    return new_alerts


def _send_pending_alerts(ssn, alert_plugins):
    """ Send pending alerts
    :param ssn: Database session
    :type ssn: sqlalchemy.orm.session.Session
    :param alert_plugins: Application config for alerts
    :type alert_plugins: list[alerts.AlertPlugin]
    :returns: The number of alerts sent
    :rtype: int
    """
    # Fetch all alerts which were not reported
    pending_alerts = ssn.query(models.Alert)\
        .filter(models.Alert.reported == False)\
        .all()

    # Report them one by one
    for a in pending_alerts:
        logger.debug(u'Sending alert #{id}: server={server}, service={service}, [{channel}/{event}]'.format(id=a.id, server=a.server, service=a.service, channel=a.channel, event=a.event))

        # Prepare alert message
        alert_message = unicode(a) + "\n"
        if a.service and a.service.state:
            s = a.service.state
            alert_message += u"Current: {}: {}\n".format(s.state, s.info)

        # Potential exceptions are handled & logged down there

        alerts.send_alert_with_plugins(alert_plugins, alert_message)