Skip to content

Instantly share code, notes, and snippets.

@shiplu

shiplu/stoptest.py

Last active Jun 30, 2020
Embed
What would you like to do?
Gracefully stop a zerorpc server
"""
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