【问题标题】:How make a python windows service of a flask/gevent.socketio server?如何制作 flask/gevent.socketio 服务器的 python windows 服务?
【发布时间】:2013-02-13 21:22:59
【问题描述】:

我有一个烧瓶/gevent SocketIOServer,需要让它作为服务工作:

class TeleportService(win32serviceutil.ServiceFramework):
    _svc_name_ = "TeleportServer"
    _svc_display_name_ = "Teleport Database Backup Service"
    _svc_description_ = "More info at www.elmalabarista.com/teleport"

    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):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, ''))

        self.ReportServiceStatus(win32service.SERVICE_RUNNING)

        runServer()


@werkzeug.serving.run_with_reloader
def runServer():
    print 'Listening on %s...' % WEB_PORT
    ws = SocketIOServer(('0.0.0.0', WEB_PORT),
        SharedDataMiddleware(app, {}),
        resource="socket.io",
        policy_server=False)

    gevent.spawn(runTaskManager).link_exception(lambda *args: sys.exit("important_greenlet died"))

    ws.serve_forever()

但是,我不知道如何从 SvcStop 停止它,并且运行它会出现奇怪的行为,即在 runserver 被杀死之后,服务解析命令行参数发生。这意味着烧瓶服务器运行,我可以从网络浏览器访问,但服务管理器将其列为“未启动”。比如在命令行中运行:

C:\Proyectos\TeleportServer>python service.py uninstall <--BAD PARAM, TO MAKE IT OBVIOUS
2013-02-13 16:19:30,786 - DEBUG: Connecting to localhost:9097
 * Restarting with reloader
2013-02-13 16:19:32,650 - DEBUG: Connecting to localhost:9097
Listening on 5000...
Growl not available: Teleport Backup Server is started
KeyboardInterrupt <--- HERE I INTERRUPT WITH CTRL-C
Unknown command - 'uninstall'
Usage: 'service.py [options] install|update|remove|start [...]|stop|restart [...
]|debug [...]'
Options for 'install' and 'update' commands only:
 --username domain\username : The Username the service is to run under
 --password password : The password for the username
 --startup [manual|auto|disabled] : How the service starts, default = manual
 --interactive : Allow the service to interact with the desktop.
 --perfmonini file: .ini file to use for registering performance monitor data

建议删除实时重新加载器,这是留下的代码。还是一样的问题

def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_, ''))

#self.timeout = 640000    #640 seconds / 10 minutes (value is in milliseconds)
self.timeout = 6000     #120 seconds / 2 minutes
# This is how long the service will wait to run / refresh itself (see script below)
notify.debug("Starting service")

ws = getServer()

while 1:
    # Wait for service stop signal, if I timeout, loop again
    gevent.sleep(0)
    rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout)
    # Check to see if self.hWaitStop happened
    if rc == win32event.WAIT_OBJECT_0:
        # Stop signal encountered
        notify.debug("Stopping service")
        ws.kill()
        servicemanager.LogInfoMsg("TeleportService - STOPPED!")  #For Event Log
        break
    else:
        notify.debug("Starting web server")
        ws.serve_forever()

【问题讨论】:

    标签: python windows windows-services flask gevent-socketio


    【解决方案1】:

    要从 SvcStop 停止它,您需要在全局变量中存储对“ws”的引用(也就是说,以后可以在某个地方检索它)。 AFAIK "ws.kill()" 然后应该结束循环。

    run_with_reloader 装饰器似乎会立即运行被装饰的函数,这可以解释为什么在运行 Web 服务器后才处理命令行。你需要自动重新加载吗,貌似装饰器只有在你需要重新加载的时候才需要。

    更新:添加示例服务代码

    在不使用烧瓶或 gevent 的项目中,我使用类似这样的东西(删除了很​​多细节):

    class Service (win32serviceutil.ServiceFramework):
    
       def __init__(self, *args, **kwds):
           self._mainloop = None
           win32serviceutil.ServiceFramework.__init__(self, *args, **kwds)
    
       def SvcStop(self):
           self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
    
           if self._mainloop is not None:
               self._mainloop.shutdown()
    
    
        def SvcStart(self):
            self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
            self._mainloop = ... .MainLoop()
            self.ReportServiceStatus(win32service.SERVICE_RUNNING)
            try:
                self._mainloop.run_forever()
    
            finally:
                self.ReportServiceStatus(win32service.SERVICE_STOPPED)
    
    win32serviceutil.HandleCommandLine(Service)
    

    【讨论】:

    • 我这样做了,并且仍然让 Web 服务器在服务代码之前运行。我删除了 run_with_reloader 并返回 ws。
    • 我必须注意,尽管这段代码在一般情况下是正确的,但不能解决让它在 gevent-socketio 的上下文中工作的问题
    【解决方案2】:

    方法serve_forever来自BaseServer.serve_forever。要阻止它,您必须调用 BaseServer.shutdown() 或其派生词。

    简而言之,您必须在全局范围内声明ws。将此代码放在 Service 类定义之前是一种方法。

    ws = None
    

    然后将您的 Service.SvcStop 实现更改为:

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
    
        #Tell the serve_forever() loop to stop and wait until it does. 
        ws.shutdown()
    

    由于ws.shutdown() 已经在等待侦听器停止,您可以删除self.hWaitStop,除非您在代码的其他地方使用它。

    需要 Python 2.6+

    【讨论】:

    • self._mainloop 来自哪里?
    【解决方案3】:

    我无法在request之外的Flask中访问WSGIRequestHandler,所以我使用Process

    import win32serviceutil
    import win32service
    import win32event
    import servicemanager
    from multiprocessing import Process
    
    from app import app
    
    
    class Service(win32serviceutil.ServiceFramework):
        _svc_name_ = "TestService"
        _svc_display_name_ = "Test Service"
        _svc_description_ = "Tests Python service framework by receiving and echoing messages over a named pipe"
    
        def __init__(self, *args):
            super().__init__(*args)
    
        def SvcStop(self):
            self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
            self.process.terminate()
            self.ReportServiceStatus(win32service.SERVICE_STOPPED)
    
        def SvcDoRun(self):
            self.process = Process(target=self.main)
            self.process.start()
            self.process.run()
    
        def main(self):
            app.run()
    
    
    if __name__ == '__main__':
        win32serviceutil.HandleCommandLine(Service)
    

    【讨论】:

      猜你喜欢
      • 2019-09-04
      • 2012-01-14
      • 1970-01-01
      • 1970-01-01
      • 2017-03-17
      • 1970-01-01
      • 2021-10-12
      • 2020-10-22
      • 2010-10-24
      相关资源
      最近更新 更多