9

フラスコ/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 が強制終了された後にコマンド ライン パラメータのサービス解析が行われるという奇妙な動作が発生します。これは、flask サーバーが実行されていることを意味します。Web ブラウザーからアクセスできますが、Service Manager には「開始されていません」と表示されます。たとえば、コマンド ラインで次のように実行します。

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()
4

3 に答える 3

2

SvcStop から停止するには、"ws" への参照をグローバル変数 (つまり、後で取得できる場所) に格納する必要があります。私の知る限り、「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)
于 2013-02-26T15:37:01.767 に答える
0

メソッドserve_foreverはから来ていBaseServer.serve_foreverます。それを止めるには、それを呼び出すBaseServer.shutdown()か、その派生物を呼び出す必要があります。

wsつまり、グローバルスコープで宣言する必要があります。このコードをServiceクラス定義の前に置くことは、それを行う1つの方法です。

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ます。

Python2.6以降が必要

于 2013-02-27T21:12:13.397 に答える