I am trying to make use of the pywin32 module to make a windows service that can kill and restart a process when a specific event is written to a log.
I'm ok with creating, declaring, and running the service but despite the fact that it launches on the event (ie timeout in the log), the service doesn't properly kill the task.
import win32service
import win32serviceutil
import win32api
import win32con
import win32event
import win32evtlogutil
from subprocess import Popen
import os, sys, string, time
import datetime
log_dir = "C:/Blablavla"
log_filename = "log"
error_strings = ("timeout", "FATAL", "error")
service_timeout = 600000
service_restart = 'batch.bat'
restart_required = False
# Make stderr and stdout will never been writen
sys.stdout = sys.stderr = open('nul', 'w')
class aservice(win32serviceutil.ServiceFramework):
_svc_name_ = "webcomRestart"
_svc_display_name_ = "restart webcom"
_svc_description_ = "restart when ssh error occurs (timeout, fatal errors,...)"
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):
import servicemanager
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_, ''))
self.timeout = service_timeout
while 1:
restart_required = False
# Wait for service stop signal, if I timeout, loop again
rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout)
# Check to see if self.hWaitStop happened
if rc == win32event.WAIT_OBJECT_0:
# Stop signal encountered
servicemanager.LogInfoMsg("webComRestart - STOPPED")
break
else:
# servicemanager.LogInfoMsg("aservice - is alive and well")
os.chdir(log_dir)
with open(log_filename, 'r') as f:
for line in f.readlines():
if any(s in line for s in error_strings):
restart_required = True
if restart_required:
#execute webcom reload
#note: I can see that in the event observer
servicemanager.LogInfoMsg("WebCom Restart attempt")
#Next command has no effect, that's my problem
p = Popen('taskkill /IM BaiWebCom.exe', shell=False)
stdout, stderr = p.communicate()
# Write trace of service action
with open("trace.txt", "a") as tracefile:
tracefile.write(str(datetime.datetime.now())+'\n')
# erase log file
with open(log_filename, 'w'): pass
def ctrlHandler(ctrlType):
return True
if __name__ == '__main__':
win32api.SetConsoleCtrlHandler(ctrlHandler, True)
win32serviceutil.HandleCommandLine(aservice)
Can someone Help?