Пример #1
0
 def error(self, msg: str) -> None:
     # Log messages go to the Windows APPLICATION log.
     # noinspection PyUnresolvedReferences
     s = "{}: {}".format(self.fullname, msg)
     servicemanager.LogErrorMsg(s)
     if self.debugging:
         log.warning(s)
Пример #2
0
    def SvcDoRun(self):
        servicemanager.LogMsg(
            servicemanager.EVENTLOG_INFORMATION_TYPE,
            servicemanager.PYS_SERVICE_STARTED,
            (self._svc_name_, '')
        )
        
        ip, port, key = getconfig()
        self.packet = n2packet(key)
        source = win32(self.packet)
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        while True:
            sleeptime = 27
            try:
                source.run()
            except:
                servicemanager.LogErrorMsg("error in main loop, retrying in 5 seconds\n\n%s" % traceback.format_exc())
                sleeptime = 5

            s.sendto(self.packet.packet(), (ip, port))
            ret = win32event.WaitForSingleObject(self.hWaitStop, sleeptime*1000)
            if ret == win32event.WAIT_OBJECT_0:
                servicemanager.LogMsg(
                    servicemanager.EVENTLOG_INFORMATION_TYPE,
                    servicemanager.PYS_SERVICE_STOPPED,
                    (self._svc_name_, '')
                )
                sys.exit(0)
Пример #3
0
    def main(self):
        """
        Primary Windows entry point

        Loads settings file location and port number from env vars if they
        are set. Otherwise falls back on defaults.

        - ``SGJIRA_SETTINGS_FILE``: defaults to settings.py located in the root
          of the sg-jira-bridge application directory
        - ``SGJIRA_PORT_NUMBER``: defaults to port 9090
        """
        # load the location of the settings file. If no env var is set, fall
        # back on a settings file located in the root of this location.
        port_number = os.environ.get("SGJIRA_PORT_NUMBER", 9090)
        settings_path = os.environ.get("SGJIRA_SETTINGS_FILE")
        if not settings_path:
            settings_path = os.path.join(
                os.path.dirname(os.path.abspath(__file__)), "settings.py")
        servicemanager.LogInfoMsg(
            "Starting up on port number %s using settings at %s" %
            (port_number, settings_path))
        try:
            import webapp

            webapp.run_server(
                port=port_number,
                settings=settings_path,
            )
        except Exception as e:
            servicemanager.LogErrorMsg("Unable to start %s: %s" %
                                       (self._svc_name_, e))
Пример #4
0
    def _get_panoptes_url(self):
        """Read the Panoptes URL from the registry and return it.

		If the registry key could not be found, shut down the service.
		"""

        url = None

        try:
            key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, self.REGISTRY_KEY,
                                 0, winreg.KEY_READ)
        except WindowsError:
            pass
        else:
            try:
                subkey_data = winreg.QueryValueEx(key,
                                                  self.REGISTRY_URL_SUBKEY)
            except WindowsError:
                pass
            else:
                try:
                    url = str(subkey_data[0])
                except (IndexError, TypeError):
                    pass

        if not url:
            servicemanager.LogErrorMsg(
                "Unable to find the PanoptesURL registry key")
            self.SvcStop()
        return url
Пример #5
0
    def SvcDoRun(self):
        import servicemanager

        # log a service started message
        servicemanager.LogMsg(
            servicemanager.EVENTLOG_INFORMATION_TYPE,
            servicemanager.PYS_SERVICE_STARTED,
            (self._svc_name_, ' (%s)' % self._svc_display_name_))

        while 1:
            self.thread_event = Event()
            self.thread_event.set()
            try:
                self.bottle_srv = BottleWsgiServer(self.thread_event)
                self.bottle_srv.start()
            except Exception, info:
                errmsg = getTrace()
                servicemanager.LogErrorMsg(errmsg)
                self.SvcStop()

            rc = win32event.WaitForMultipleObjects((self.hWaitStop, ), 0,
                                                   win32event.INFINITE)
            if rc == win32event.WAIT_OBJECT_0:
                # user sent a stop service request
                self.SvcStop()
                break
Пример #6
0
    def restart(self):
        if not self._can_restart():
            servicemanager.LogWarningMsg(
                u"`{0}` reached the limit of restarts ({1} tries during the last {2}s"
                u" (max authorized: {3})). Not restarting...".format(
                    self._name, len(self._restarts), self._RESTART_TIMEFRAME,
                    self._max_restarts))
            self._process.is_enabled = False
            return

        try:
            # Make a new proc instances because multiprocessing
            # won't let you call .start() twice on the same instance.
            if self._process.is_alive():
                self._process.terminate()

            # Recreate a new process
            self._process = self._process.__class__(self._process.config,
                                                    self._process.hostname,
                                                    **self._process.options)
            self._process.start()
        except WindowsError as e:  # pylint: disable=E0602
            servicemanager.LogErrorMsg(
                u"Fail to restart `{process}`: {err}".format(
                    process=self._name, err=e))

        self._restarts.append(time.time())
Пример #7
0
    def SvcDoRun(self):
        """Core service logic"""

        # Go to module install directory
        install_dir_ = os.path.dirname(__file__)
        if install_dir_:
            os.chdir(install_dir_)

        # "Service started" message to Windows Event Log
        sm.LogMsg(                          # pylint: disable-msg=E1101
            sm.EVENTLOG_INFORMATION_TYPE,   # pylint: disable-msg=E1101
            sm.PYS_SERVICE_STARTED,         # pylint: disable-msg=E1101
            (self._svc_name_, ""))

        try:
            rc_ = None
            # if the stop event hasn't been fired keep looping
            while rc_ != w32e.WAIT_OBJECT_0:    # pylint: disable-msg=E1101

                # Actuate job
                self.__actuate()

                # Pause for EXEC_INTERVAL and listen for a stop event every STOP_CHECK_INTERVAL
                ei_ = getattr(_conf.m, "EXEC_INTERVAL", EXEC_INTERVAL)
                si_ = getattr(_conf.m, "STOP_CHECK_INTERVAL", STOP_CHECK_INTERVAL)
                ic_ = ei_ / si_
                while ic_ > 0 and rc_ != w32e.WAIT_OBJECT_0:    # pylint: disable-msg=E1101
                    ic_ -= 1
                    rc_ = w32e.WaitForSingleObject(self.hWaitStop, si_) # pylint: disable-msg=E1101

        except Exception: # pylint: disable-msg=W0703
            sm.LogErrorMsg(traceback.format_exc())  # pylint: disable-msg=E1101
Пример #8
0
    def SvcDoRun(self):
        import servicemanager

        self._log.info("%s - Starting" % self._svc_name_)
        servicemanager.LogInfoMsg("%s - Starting" % self._svc_name_)
        try:
            # Config file name is hardcoded
            config_file = "config.cfg"

            # Try to find the configuration file looking up
            # from the script file
            # It's a messy kludge but I couldn't find better
            import os.path
            path = os.path.abspath(os.path.dirname(__file__))

            last_path = path
            self._log.info("%s - Searching for config in (%s)" %
                           (self._svc_name_, last_path))
            while not os.access(path + "/" + config_file, os.R_OK):
                (path, _) = os.path.split(path)
                if path == last_path:
                    last_path = None
                    print "Not found aborting"
                    break
                last_path = path
                self._log.info("%s - Searching for config in (%s)" %
                               (self._svc_name_, last_path))

            if last_path == None:
                self._log.error(
                    "%s - Unable to locate configuration file (%s)" %
                    (self._svc_name_, config_file))
                servicemanager.LogErrorMsg(
                    "%s - Unable to locate configuration file (%s)" %
                    (self._svc_name_, config_file))
                return

            # Change working directory
            os.chdir(last_path)

            # init python logging (Anything logged before that had been lost)
            logging.config.fileConfig(config_file)
            self._log.info("%s - Changing working directory to (%s)" %
                           (self._svc_name_, last_path))

            # Start
            self._log.info("%s - Starting Moniteur" % self._svc_name_)
            self.application = Moniteur(config_file)
            self.application.start()

            self._log.info("%s - Started" % self._svc_name_)
            servicemanager.LogInfoMsg("%s - Started" % self._svc_name_)

            while self.isAlive:
                time.sleep(5)

            self._log.info("%s - Stopping" % self._svc_name_)
            servicemanager.LogInfoMsg("%s - Stopping" % self._svc_name_)
        except:
            pass
Пример #9
0
    def SvcDoRun(self):
        configfile = win32serviceutil.GetServiceCustomOption(
            self._svc_name_, "config")
        os.chdir(os.path.dirname(configfile))
        self.log("Using config file %s." % configfile)
        self.log("Logging at %s." % os.getcwd())
        self.ReportServiceStatus(win32service.SERVICE_RUNNING)

        from microscope.device_server import (
            serve_devices,
            validate_devices,
            DeviceServerOptions,
        )

        options = DeviceServerOptions(
            config_fpath=configfile,
            logging_level=logging.INFO,
        )

        try:
            devices = validate_devices(configfile)
            serve_devices(devices, options, self.stop_event)
        except Exception as e:
            servicemanager.LogErrorMsg(str(e))
            # Exit with non-zero error code so Windows will attempt to restart.
            sys.exit(-1)
        self.log("Service shutdown complete.")
        self.ReportServiceStatus(win32service.SERVICE_STOPPED)
Пример #10
0
    def SvcDoRun(self):
        if hasattr(sys, "frozen"):
            this_dir = os.path.dirname(win32api.GetModuleFileName(None))
        else:
            this_dir = os.path.dirname(os.path.abspath(__file__))
        # TODO: maybe it is better to run this in a job object too
        with open(os.path.join(this_dir, 'npm.log'), 'w') as npm_log:
            subprocess.check_call('npm install',
                                  cwd=this_dir,
                                  shell=True,
                                  stdin=None,
                                  stdout=npm_log,
                                  stderr=subprocess.STDOUT)

        security_attributes = win32security.SECURITY_ATTRIBUTES()
        security_attributes.bInheritHandle = True
        startup = win32process.STARTUPINFO()
        startup.dwFlags |= win32process.STARTF_USESTDHANDLES
        startup.hStdInput = None
        startup.hStdOutput = win32file.CreateFile(
            os.path.join(this_dir, "service_stderr.log"),
            win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ,
            security_attributes, win32file.CREATE_ALWAYS, 0, None)
        startup.hStdError = win32file.CreateFile(
            os.path.join(this_dir, "service_stdout.log"),
            win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ,
            security_attributes, win32file.CREATE_ALWAYS, 0, None)
        (hProcess, hThread, processId, threadId) = win32process.CreateProcess(
            None, r'"C:\Program Files\nodejs\node.exe" node_worker.js', None,
            None, True, win32process.CREATE_SUSPENDED
            | win32process.CREATE_BREAKAWAY_FROM_JOB, None, this_dir, startup)

        assert not win32job.IsProcessInJob(hProcess, None)

        self.hJob = win32job.CreateJobObject(None, "")
        extended_info = win32job.QueryInformationJobObject(
            self.hJob, win32job.JobObjectExtendedLimitInformation)
        extended_info['BasicLimitInformation'][
            'LimitFlags'] = win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | win32job.JOB_OBJECT_LIMIT_BREAKAWAY_OK
        win32job.SetInformationJobObject(
            self.hJob, win32job.JobObjectExtendedLimitInformation,
            extended_info)
        win32job.AssignProcessToJobObject(self.hJob, hProcess)

        win32process.ResumeThread(hThread)
        win32api.CloseHandle(hThread)

        signalled = win32event.WaitForMultipleObjects(
            [self.hWaitStop, hProcess], False, win32event.INFINITE)
        if signalled == win32event.WAIT_OBJECT_0 + 1 and win32process.GetExitCodeProcess(
                hProcess) != 0:
            servicemanager.LogErrorMsg(
                self._svc_name_ + " process exited with non-zero status " +
                str(win32process.GetExitCodeProcess(hProcess)))
        win32api.CloseHandle(hProcess)
        win32api.CloseHandle(self.hJob)
        win32api.CloseHandle(self.hWaitStop)
        win32api.CloseHandle(startup.hStdOutput)
        win32api.CloseHandle(startup.hStdError)
Пример #11
0
 def error(self, msg, codErro):
     servicemanager.LogErrorMsg(msg)
     self.ReportServiceStatus(
         win32service.SERVICE_STOPPED,
         win32ExitCode=winerror.ERROR_SERVICE_SPECIFIC_ERROR,
         svcExitCode=codErro)
     logging.error("%s (Cod erro: %s)" % (msg, codErro))
     os._exit(codErro)
Пример #12
0
    def SvcDoRun(self):

        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_, ''))

        try:
            self.main()
        except Exception as e:
            output = io.StringIO()

            traceback.print_tb(e.__traceback__, file=output)

            servicemanager.LogErrorMsg('ERROR: %s' % e)
            servicemanager.LogErrorMsg('ERROR: %s' % output.getvalue())

            output.close()
Пример #13
0
 def emit(self, record):
     try:
         msg = self.format(record)
         if record.levelno >= logging.ERROR:
             servicemanager.LogErrorMsg(msg)
         elif record.levelno >= logging.INFO:
             servicemanager.LogiNFOMsg(msg)
     except Exception:
         pass
Пример #14
0
 def SvcStop(self):
     try:
         self.isAlive = False
         self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
         win32event.SetEvent(self.hWaitStop)
         os._exit(0)
     except:
         servicemanager.LogErrorMsg(traceback.format_exc())
         os._exit(0)
Пример #15
0
 def log(self, level, msg):
     if level == "error":
         servicemanager.LogErrorMsg(msg)
     elif level == "warn":
         servicemanager.LogWarningMsg(msg)
     elif level == "notice":
         servicemanager.LogInfoMsg(msg)
     else:
         pass
Пример #16
0
 def error(self, msg: str) -> None:
     """
     Write an error message to the Windows Application log
     (± to the Python disk log).
     """
     # noinspection PyUnresolvedReferences
     servicemanager.LogErrorMsg(str(msg))
     if self.debugging:
         log.error(msg)
Пример #17
0
 def __init__(self, args):
     win32serviceutil.ServiceFramework.__init__(self, args)
     self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
     try:
         self.config = configparser.ConfigParser()
         self.config.read('/repos/Nowcast/config/configNowcasting.ini')
     except Exception as e:
         servicemanager.LogErrorMsg(traceback.format_exc())
         logging.info("Error in init: %s", e)
         raise
Пример #18
0
 def SvcDoRun(self):
     servicemanager.LogInfoMsg("starting...")
     self.observerManager = serviceconfig.load()
     if self.observerManager:
         self.observerManager.start()
         win32event.SetEvent(self.hWaitStop)
     else:
         errorMessage = serviceconfig.getLogErrorMsg()
         if errorMessage != None:
             servicemanager.LogErrorMsg(errorMessage)
Пример #19
0
 def log(message: str, msg_type: int = INFO):
     """Log a message to the Windows Event Log."""
     if msg_type == INFO:
         servicemanager.LogInfoMsg(str(message))
     if msg_type == WARN:
         servicemanager.LogWarningMsg(str(message))
     elif msg_type == ERR:
         servicemanager.LogErrorMsg(str(message))
     else:
         servicemanager.LogMsg(str(message))
Пример #20
0
 def SvcStop(self):
     try:
         print("Stopping...")
         servicemanager.LogInfoMsg("Stopping...")
         self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
         win32event.SetEvent(self.hWaitStop)
         self.isAlive = False
     except Exception as e:
         print("Error: " + str(e))
         servicemanager.LogErrorMsg("Error: " + str(e))
Пример #21
0
 def __init__(self, args):
     try:
         win32serviceutil.ServiceFramework.__init__(self,args)
         servicemanager.LogInfoMsg("Logging to: " + log_location)
         print("Initialising...")
         servicemanager.LogInfoMsg("Initialising...")
         self.hWaitStop = win32event.CreateEvent(None,0,0,None)
         self.isAlive = True
     except Exception as e:
         print("Error: " + str(e))
         servicemanager.LogErrorMsg("Error: " + str(e))
Пример #22
0
 def SvcDoRun(self):
     try:
         print("Starting...")
         servicemanager.LogInfoMsg("Starting...")
         servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                               servicemanager.PYS_SERVICE_STARTED,
                               (self._svc_name_,''))
         self.main()
     except Exception as e:
         print("Error: " + str(e))
         servicemanager.LogErrorMsg("Error: " + str(e))
Пример #23
0
 def SvcDoRun(self):
     servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                           servicemanager.PYS_SERVICE_STARTED,
                           (self._svc_name_, ''))
     servicemanager.LogInfoMsg('ceajenkins before main')
     try:
         self.main()
     except:
         servicemanager.LogErrorMsg(traceback.format_exc())
         sys.exit(-1)
     servicemanager.LogInfoMsg('normal exit')
Пример #24
0
 def SvcDoRun(self):
     rc = None
     while rc != win32event.WAIT_OBJECT_0:
         pythoncom.CoInitialize()
         try:
             script.main()
         except:
             servicemanager.LogErrorMsg(traceback.format_exc())
             continue
         rc = win32event.WaitForSingleObject(self.hWaitStop, 5000)
         pythoncom.CoUninitialize()
Пример #25
0
 def SvcDoRun(self):
     self.isAlive = True
     servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, ''))
     #New Additions for service stop issue
     try:
         self.main()
     except:
         servicemanager.LogErrorMsg(traceback.format_exc()) # if error print it to event log
         os._exit(-1)#return some value other than 0 to os so that service knows to restart
     #self.main()
     win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
Пример #26
0
 def SendSmsBack(self, send_message):  #发短信
     try:
         servicemanager.LogInfoMsg('发短信:%s' % send_message)
         for phone_num in SasConfig.phone_num:
             try:
                 self.SendSms2Server(send_message, phone_num)
             except Exception, msg:
                 #失败后尝试重新发一次
                 time.sleep(30)
                 self.SendSms2Server(send_message, phone_num)
     except Exception, msg:
         servicemanager.LogErrorMsg('发短信失败,错误信息:%s' % str(msg))
Пример #27
0
 def _check_collector_blocked(self):
     if self._collector_heartbeat.poll():
         while self._collector_heartbeat.poll():
             self._collector_heartbeat.recv()
         self._collector_failed_heartbeats = 0
     else:
         self._collector_failed_heartbeats += 1
         if self._collector_failed_heartbeats > self._max_failed_heartbeats:
             servicemanager.LogErrorMsg(
                 u"`{}` was unresponsive for too long. Restarting...".
                 format(u'collector'))
             self.procs['collector'].restart()
             self._collector_failed_heartbeats = 0
Пример #28
0
    def LaunchModelScript(self):
        logging.info("Initiate the Model {0}".format(datetime.datetime.now()))

        ## -- The KloFlow Model -- ##
        try:
            self.forecasts.fcstDownloadData()
        except:
            logging.info(
                "Error running the Bloomberg data program for macro forecasts: {0}"
                .format(traceback.format_exc()))
            self.sendErrorMail(str(traceback.format_exc()))
            servicemanager.LogErrorMsg(traceback.format_exc())
            raise
Пример #29
0
 def run(self):
     while self._start_running:
         try:
             self.server = SimpleXMLRPCServer.SimpleXMLRPCServer(
                 ("", 8080), requestHandler=SilentRequestHandler)
             self.server.register_instance(DDESpy(self.servicemanager))
             self.server.serve_forever()
         except ShutdownError, e:
             return
         except Exception, e:
             import servicemanager
             servicemanager.LogErrorMsg("Caught exception: %s" % str(e))
             time.sleep(1)
Пример #30
0
 def delete_file(self, fname):
     if os.path.exists(fname):
         try:
             os.remove(fname)
             self.deleted_list.append(fname)
         except OSError:
             try:
                 import servicemanager
                 servicemanager.LogErrorMsg(
                     "BackupHistoryManager: could not delete file %s" %
                     fname)
             except ImportError:
                 pass