-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtzrpc_server.py
More file actions
69 lines (60 loc) · 2.79 KB
/
tzrpc_server.py
File metadata and controls
69 lines (60 loc) · 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#
# Written by: Carlos Bazaga
#
# Licensed under BSD 2-Clause
#
import tprocessing as tp
import threading as th
import zerorpc
import gevent
import random
class Tzrpc_server(tp.Tprocess):
"""Service process for a "ZeroRPC" server."""
def __init__(self, name, protocol, address, port, catalog):
"""Return a process ready to start a "ZeroRPC" server."""
tp.Tprocess.__init__(self)
self.daemon = True # Set the proces as "Daemon".
self.name = name # Set the server name.
self.protocol = protocol # Connection protocol for the RPC server.
self.address = address # Connection address for the RPC server.
self.port = port # Connection port for the RPC server.
self.catalog = catalog # Object containing the methods to be shared by the RPC server.
self.binding = "{0}://{1}:{2}".format(self.protocol, self.address, self.port)
# Communication channel:
self._signal = tp.Pipe(False) # "Stop server" signal pipe.
self._stopped = False # Flag the server as stopped.
def run(self):
# """Create and run the server."""
from gevent import monkey; monkey.patch_all(socket=False, dns=False, time=True, select=False,
thread=False, os=False, ssl=True, httplib=False,
subprocess=False, sys=False, aggressive=False,
Event=False)
# Create the server.
self._server = zerorpc.Server(self.catalog)
self._server.bind(self.binding)
# Set a service thread that waits for "stop" signal.
_waiter = th.Thread(target=self.__wait, name='Killer')
_waiter.daemon = True # Set the thread as "Daemon".
_waiter.start() # Start the service.
# Run the server.
self._server.run()
# Close the pipe.
self._signal[0].close()
self._signal[1].close()
def stop(self):
"""Request to stop the server."""
if not self._stopped:
self._signal[1].send('This message awakes "__wait"')
self._stopped = True
def __wait(self):
"""Wait the signal to stop the server."""
self._signal[0].recv()
try:
self._server.stop()
except zerorpc.gevent.hub.LoopExit as err:
pass # Ignore warning message cast as exception by "gevent"
def Launch(name, protocol, address, port, catalog):
"""Create a "ZeroRPC" server running in an independent process."""
Zserver = Tzrpc_server(name, protocol, address, port, catalog)
Zserver.start()
return Zserver