-
Notifications
You must be signed in to change notification settings - Fork 29
/
service_win32.py
85 lines (69 loc) · 2.55 KB
/
service_win32.py
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
83
84
85
import win32serviceutil
import win32service
import win32event
import win32evtlogutil
import servicemanager
import os
import sys
import logging
from threading import Thread
from mamonsu.lib.config import Config
from mamonsu.lib.supervisor import Supervisor
config = None
class MamonsuSvc(win32serviceutil.ServiceFramework):
_svc_name_ = 'mamonsu'
_svc_description_ = 'monitoring agent: mamonsu'
_svc_display_name_ = 'monitoring agent: mamonsu'
_svc_deps_ = ['EventLog']
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
win32evtlogutil.ReportEvent(
self._svc_name_,
servicemanager.PYS_SERVICE_STARTED,
0,
servicemanager.EVENTLOG_INFORMATION_TYPE,
(self._svc_name_, ''))
supervisor = Supervisor(config)
win32evtlogutil.ReportEvent(
self._svc_name_,
servicemanager.PYS_SERVICE_STOPPED,
0,
servicemanager.EVENTLOG_INFORMATION_TYPE,
(self._svc_name_, ''))
thread = Thread(target=supervisor.start)
thread.daemon = True
thread.start()
while True:
rc = win32event.WaitForSingleObject(
self.hWaitStop, win32event.INFINITE)
if rc == win32event.WAIT_OBJECT_0:
win32evtlogutil.ReportEvent(
self._svc_name_,
servicemanager.PYS_SERVICE_STOPPED,
0,
servicemanager.EVENTLOG_INFORMATION_TYPE,
(self._svc_name_, ''))
break
#if __name__ == '__main__':
# win32serviceutil.HandleCommandLine(MamonsuSvc)
if __name__ == '__main__':
# determine if application is a script file or frozen exe
if getattr(sys, 'frozen', False):
exe_dir = os.path.dirname(sys.executable)
elif __file__:
# exe_dir = C:\WINDOWS\system32 for service
exe_dir = os.path.dirname(os.path.abspath(__file__))
# initializing in this place for logging
config_file = os.path.join(exe_dir, 'agent.conf')
config = Config(config_file)
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(MamonsuSvc)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(MamonsuSvc)