This repository has been archived by the owner on May 21, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
pubsub.py
229 lines (179 loc) · 7.5 KB
/
pubsub.py
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import json
import logging
import zmq
from zmq.error import ZMQError
from zmq.eventloop.zmqstream import ZMQStream
from zmq.eventloop import ioloop
from django.utils.encoding import force_bytes
from django.core.serializers.json import DjangoJSONEncoder
from . import exceptions as ex
from .settings import (
SUBSCRIBER_ADDRESS, PUBLISHER_ADDRESS,
DIRECTOR_SUBSCRIBER_ADDRESS, DIRECTOR_PUBLISHER_ADDRESS)
logger = logging.getLogger(__name__)
LOG_LEVELS = {
'debug': logger.debug,
'info': logger.info,
'error': logger.error,
}
class PubSub(object):
BIND = 'bind'
CONNECT = 'connect'
ioloop_installed = False
connections = None
bridges = None
def __init__(self, loop=None):
self.context = zmq.Context()
self.connections = {}
self.bridges = {}
self.loop = loop or ioloop.IOLoop.instance()
def log(self, level, message):
LOG_LEVELS[level](u'[%s] %s' % (id(self), message))
# CONNECTION -------------------------------------------------------------
def get_connection(self, mode, address, bind=False):
# Lets see if we have a connection to the address already (also respect
# if we should bind or connect and the zmq socket mode)
connection = self.connections.setdefault(
mode, {}).setdefault(address, {}).get(bind, None)
if connection is None:
try:
connection = self.context.socket(mode)
if bind:
connection.bind(address)
else:
connection.connect(address)
except ZMQError as e:
raise ex.OmnibusException(e)
# Remember connection in central dict.
self.connections[mode][address][bind] = connection
# Return the requested connection.
return connection
def send(self, msg):
"""
`send` is used to publish a message to a zmq connection. A specific
publisher can be provided, if no publisher is provived, we request
the default one.
"""
try:
self.log('debug', u'send {0} to {1}'.format(msg, PUBLISHER_ADDRESS))
publisher = self.get_connection(zmq.PUB, PUBLISHER_ADDRESS)
publisher.send_unicode(msg)
except ZMQError as e:
raise ex.OmnibusPublisherException(e)
return True
def publish(self, channel, payload_type, payload=None, sender=None):
"""
`publish` is a highlevel method to publish stuff. It handles the json
converting and ensures the payload has the correct data type.
"""
if payload is None:
payload = {}
if not isinstance(payload, dict):
raise ex.OmnibusDataException(
'Invalid payload, needs to be a dict: {0}'.format(type(payload)))
try:
self.log(
'debug',
u'publish to {0} (payload_type:{1}, payload:{2}, sender:{3})'.format(
channel, payload_type, payload, sender))
return self.send(u'{0}:{1}'.format(
channel,
json.dumps({
'sender': sender,
'type': payload_type,
'payload': payload
}, cls=DjangoJSONEncoder)
))
except (TypeError, ValueError) as e:
raise ex.OmnibusDataException(e)
# SUBSCRIBING ------------------------------------------------------------
def get_subscriber(self, callback, address=None):
"""
`get_subscriber` creates a new zmq subscriber stream. If no address is
provided, the default subscriber address is used.
"""
if address is None:
address = SUBSCRIBER_ADDRESS
try:
subscriber_socket = self.context.socket(zmq.SUB)
subscriber_socket.connect(address)
subscriber = ZMQStream(subscriber_socket, io_loop=self.loop)
subscriber.on_recv(callback)
except ZMQError as e:
raise ex.OmnibusSubscriberException(e)
# Initialize channel list
subscriber.channels = []
return subscriber
def close_subscriber(self, subscriber):
"""
`close_subscriber` closes the subscriber stream and the socket below.
"""
try:
subscriber_socket = subscriber.socket
subscriber.close()
subscriber_socket.close()
except ZMQError as e:
raise ex.OmnibusSubscriberException(e)
return True
def subscribe(self, subscriber, channel):
"""
`subscribe` is called after client connection wants to subscribe to a
channel. If the subcriber is already subscribed to a channel, it fails.
"""
if channel in subscriber.channels:
return False
try:
subscriber.setsockopt(zmq.SUBSCRIBE, force_bytes(channel))
subscriber.channels.append(channel)
except ZMQError as e:
raise ex.OmnibusSubscriberException(e)
return True
def unsubscribe(self, subscriber, channel):
"""
`unsubscribe` is called after client connection wants to unsubscribe
from a channel. If the subcriber isn't subscribed to the channel, it fails.
"""
if channel not in subscriber.channels:
return False
try:
subscriber.setsockopt(zmq.UNSUBSCRIBE, force_bytes(channel))
subscriber.channels.remove(channel)
except ZMQError as e:
raise ex.OmnibusSubscriberException(e)
return True
# BRIDGING ---------------------------------------------------------------
def init_bridge(self, in_mode, in_address, out_mode, out_address):
assert in_mode in (self.BIND, self.CONNECT), 'Invalid in_mode'
assert out_mode in (self.BIND, self.CONNECT), 'Invalid out_mode'
instances = self.bridges.setdefault(in_address, {}).setdefault(
in_mode, {}).setdefault(out_address, {}).get(out_mode, None)
if instances is None:
instances = {}
try:
instances['in'] = self.context.socket(zmq.SUB)
if in_mode == self.BIND:
instances['in'].bind(in_address)
elif in_mode == self.CONNECT:
instances['in'].connect(in_address)
instances['in'].setsockopt(zmq.SUBSCRIBE, b'')
instances['out'] = self.context.socket(zmq.PUB)
if out_mode == self.BIND:
instances['out'].bind(out_address)
elif out_mode == self.CONNECT:
instances['out'].connect(out_address)
# Transfer data from subscriber to publisher.
instances['bridge'] = ZMQStream(instances['in'], io_loop=self.loop)
instances['bridge'].on_recv(lambda msg: instances['out'].send(msg[0]))
except ZMQError as e:
raise ex.OmnibusException(e)
self.bridges[in_address][in_mode][out_address][out_mode] = instances
return instances
def init_director(self):
return self.init_bridge(
self.BIND, PUBLISHER_ADDRESS, self.BIND, SUBSCRIBER_ADDRESS)
def init_forwarder(self):
sub_forwarder = self.init_bridge(
self.CONNECT, DIRECTOR_SUBSCRIBER_ADDRESS, self.BIND, SUBSCRIBER_ADDRESS)
pub_forwarder = self.init_bridge(
self.BIND, PUBLISHER_ADDRESS, self.CONNECT, DIRECTOR_PUBLISHER_ADDRESS)
return pub_forwarder, sub_forwarder