Example #1
0
    def SvcRun(self):
        self.ReportServiceStatus(win32service.SERVICE_START_PENDING)

        import servicemanager

        parser = self._InitOptionsParser()
        (self.options, args) = parser.parse_args()

        try:
            is_debugging = servicemanager.Debugging()
        except:
            is_debugging = False

        if not is_debugging:
            # Save the current dir, or the script dir if none set (typical for services)
            script_path = os.path.dirname(__file__.replace('/', os.sep))
            # the script resides in the sbin/ambari_commons subdir
            self.options.current_dir = os.path.normpath(script_path +
                                                        "\\..\\..")
            os.chdir(self.options.current_dir)
        else:
            self.options.current_dir = os.getcwd()

        self._adjustPythonPath(self.options.current_dir)

        self.SvcDoRun()
        pass
Example #2
0
def DebugService(cls, argv=[]):
    # Run a service in "debug" mode.  Re-implements what pythonservice.exe
    # does when it sees a "-debug" param.
    # Currently only used by "frozen" (ie, py2exe) programs (but later may
    # end up being used for all services should we ever remove
    # pythonservice.exe)
    import servicemanager
    global g_debugService

    print "Debugging service %s - press Ctrl+C to stop." % (cls._svc_name_, )
    servicemanager.Debugging(True)
    servicemanager.PrepareToHostSingle(cls)
    g_debugService = cls(argv)
    # Setup a ctrl+c handler to simulate a "stop"
    win32api.SetConsoleCtrlHandler(_DebugCtrlHandler, True)
    try:
        g_debugService.SvcRun()
    finally:
        win32api.SetConsoleCtrlHandler(_DebugCtrlHandler, False)
        servicemanager.Debugging(False)
        g_debugService = None
Example #3
0
def redirectSystemStreamsIfNecessary(stdout=None, stderr=None):
	# Python programs running as Windows NT services must not send output to
	# the default sys.stdout or sys.stderr streams, because those streams are
	# not fully functional in the NT service execution environment.  Sending
	# output to them will eventually (but not immediately) cause an IOError
	# ("Bad file descriptor"), which can be quite mystifying to the
	# uninitiated.  This problem can be overcome by replacing the default
	# system streams with a stream that discards any data passed to it (like
	# redirection to /dev/null on Unix).
	#
	# However, the pywin32 service framework supports a debug mode, under which
	# the streams are fully functional and should not be redirected.
	shouldRedirect = True
	try:
		import servicemanager
	except ImportError:
		# If we can't even 'import servicemanager', we're obviously not running
		# as a service, so the streams shouldn't be redirected.
		shouldRedirect = False
	else:
		# Unlike previous builds, pywin32 builds >= 200 allow the
		# servicemanager module to be imported even in a program that isn't
		# running as a service.  In such a situation, it would not be desirable
		# to redirect the system streams.
		#
		# However, it was not until pywin32 build 203 that a 'RunningAsService'
		# predicate was added to allow client code to determine whether it's
		# running as a service.
		#
		# This program logic redirects only when necessary if using any build
		# of pywin32 except 200-202.  With 200-202, the redirection is a bit
		# more conservative than is strictly necessary.
		if servicemanager.Debugging() or \
				(hasattr(servicemanager, 'RunningAsService') and not
				servicemanager.RunningAsService()):
			shouldRedirect = False

	if shouldRedirect:
		if not stdout:
			stdout = open('nul', 'w')
		sys.stdout = stdout
		if not stderr:
			stderr = open('nul', 'w')
		sys.stderr = stderr
	return shouldRedirect
        while self.run:
            sock = pyfhelSocket(ip='202.114.40.141')
            sock.open()
            # self.socket = socket.socket()
            # self.socket.bind(('127.0.0.1', port))
            # self.socket.listen(5)
            time.sleep(2)

    def SvcStop(self):
        self.logger.info('service is stop.')
        self.socket.close()
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        self.run = False


if __name__ == '__main__':
    if len(sys.argv) == 1:
        try:
            evtsrc_dll = os.path.abspath(servicemanager.__file__)
            servicemanager.PrepareToHostSingle(encryptClient)
            servicemanager.Initialize('encryptClient', evtsrc_dll)
            servicemanager.StartServiceCtrlDispatcher()
            servicemanager.Debugging()
        except win32service.error as details:
            import winerror
            if details == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
                win32serviceutil.usage()
            else:
                win32serviceutil.HandleCommandLine(encryptClient)