watchdog-winservice.py 2.57 KB
Newer Older
Guba Sándor committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
import logging
from logging.handlers import NTEventLogHandler
from time import sleep
import os
import servicemanager
import socket
import sys
import win32event
import win32service
import win32serviceutil

logger = logging.getLogger()
fh = NTEventLogHandler(
    "CIRCLE Watchdog", dllname=os.path.dirname(__file__))
formatter = logging.Formatter(
    "%(asctime)s - %(name)s [%(levelname)s] %(message)s")
fh.setFormatter(formatter)
logger.addHandler(fh)
level = os.environ.get('LOGLEVEL', 'INFO')
logger.setLevel(level)
logger.info("%s loaded", __file__)

service_name = "circle-agent"
stopped = False

Guba Sándor committed
26

Guba Sándor committed
27 28 29
def watch():
    def check_service(service_name):
        return win32serviceutil.QueryServiceStatus(service_name)[1] == 4
Guba Sándor committed
30

Guba Sándor committed
31 32
    def start_service():
        win32serviceutil.StartService(service_name)
Guba Sándor committed
33

Guba Sándor committed
34 35 36 37 38 39 40 41
    while True:
        if not check_service(service_name):
            logger.info("Service %s is not running.", service_name)
            start_service()
        if stopped:
            return
        sleep(10)

Guba Sándor committed
42

Guba Sándor committed
43 44 45 46 47 48 49 50 51 52 53 54
class AppServerSvc (win32serviceutil.ServiceFramework):
    _svc_name_ = "circle-watchdog"
    _svc_display_name_ = "CIRCLE Watchdog"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        socket.setdefaulttimeout(60)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
Guba Sándor committed
55
        global stopped
Guba Sándor committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
        stopped = True
        logger.info("%s stopped", __file__)

    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_, ''))
        logger.info("%s starting", __file__)
        watch()


def main():
    if len(sys.argv) == 1:
        # service must be starting...
        # for the sake of debugging etc, we use win32traceutil to see
        # any unhandled exceptions and print statements.
        import win32traceutil  # noqa
        logger.info("service is starting...")

        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(AppServerSvc)
        # Now ask the service manager to fire things up for us...
        servicemanager.StartServiceCtrlDispatcher()
        logger.info("service done!")
    else:
        win32serviceutil.HandleCommandLine(AppServerSvc)

Czémán Arnold committed
83

Guba Sándor committed
84 85 86 87 88
if __name__ == '__main__':
    try:
        main()
    except (SystemExit, KeyboardInterrupt):
        raise
Czémán Arnold committed
89
    except Exception:
Guba Sándor committed
90
        logger.exception("Exception:")