Last active
April 19, 2022 19:10
-
-
Save shiplu/0f1fd2f2a06519d0530c92533e18f264 to your computer and use it in GitHub Desktop.
Gracefully stop a zerorpc server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
stoptest.py | |
Run it with zerorpc. To close press Ctrl+C or send a TERM or INT signal. | |
""" | |
import zerorpc | |
import time | |
import signal | |
import sys | |
import itertools | |
from functools import partial | |
class T(object): | |
start = None | |
@classmethod | |
def log(cls, msg): | |
now = time.time() | |
if cls.start is None: | |
cls.start = now | |
print("[%10s] %s" % ('%.06f' % (now - cls.start), msg)) | |
class Server(object): | |
def ping(self): | |
"""Play pingpong""" | |
T.log("Playing ping pong") | |
return "pong" | |
def sum(self, *nums): | |
"""Sum of numbers""" | |
T.log("Doing math") | |
return sum(nums) | |
def cleanup(self): | |
"""Do cleanup """ | |
T.log("Cleaning up in 5s") | |
zerorpc.gevent.sleep(5) | |
def main(): | |
socket = "tcp://127.0.0.1:9999" | |
server_object = Server() | |
server = zerorpc.Server(server_object, heartbeat=None) | |
server.debug = True | |
server.bind(socket) | |
def exit_gracefully(): | |
old_int_hnd.cancel() | |
zerorpc.gevent.signal(signal.SIGINT, partial(sys.exit, signal.SIGINT)) | |
old_term_hnd.cancel() | |
zerorpc.gevent.signal(signal.SIGTERM, partial(sys.exit, signal.SIGTERM)) | |
T.log("stopping server") | |
server.stop() | |
T.log("do cleanup") | |
server('cleanup') | |
zerorpc.gevent.sleep(1) | |
T.log("closing server") | |
server.close() | |
T.log("do cleanup again") | |
server('cleanup') | |
sys.exit(0) | |
old_int_hnd = zerorpc.gevent.signal(signal.SIGINT, exit_gracefully) | |
old_term_hnd = zerorpc.gevent.signal(signal.SIGTERM, exit_gracefully) | |
try: | |
T.log("Spawning server") | |
zerorpc.gevent.spawn(server.run) | |
T.log("TimeslotPlanningServer is listenning on %s" % socket) | |
for c in itertools.count(1): | |
zerorpc.gevent.sleep(5) | |
T.log("[%2s] Main Greenlet sleeping for 5s" % c) | |
except KeyboardInterrupt: | |
T.log("Received a request to terminate the server by KeyboardInterrupt!") | |
exit_gracefully() | |
T.log("Good bye!") | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment