1 import sys, os, time, md5, random
2 from mod_python import apache, util
3 import osrf.system, osrf.cache, osrf.json, osrf.conf, osrf.net, osrf.log
4 from osrf.const import OSRF_MESSAGE_TYPE_DISCONNECT, OSRF_MESSAGE_TYPE_CONNECT, \
5 OSRF_STATUS_CONTINUE, OSRF_STATUS_TIMEOUT, OSRF_MESSAGE_TYPE_STATUS
9 Proof of concept OpenSRF-HTTP multipart streaming gateway.
11 Example Apache mod_python config:
13 <Location /osrf-http-translator>
15 PythonPath "['/path/to/osrf-python'] + sys.path"
16 PythonHandler osrf.http_translator
17 PythonOption OSRF_CONFIG /path/to/opensrf_core.xml
18 PythonOption OSRF_CONFIG_CONTEXT config.gateway
19 PythonOption OSRF_CACHE_SERVERS 127.0.0.1:11211
25 OSRF_HTTP_HEADER_TO = 'X-OpenSRF-to'
26 OSRF_HTTP_HEADER_XID = 'X-OpenSRF-xid'
27 OSRF_HTTP_HEADER_FROM = 'X-OpenSRF-from'
28 OSRF_HTTP_HEADER_THREAD = 'X-OpenSRF-thread'
29 OSRF_HTTP_HEADER_TIMEOUT = 'X-OpenSRF-timeout'
30 OSRF_HTTP_HEADER_SERVICE = 'X-OpenSRF-service'
31 OSRF_HTTP_HEADER_MULTIPART = 'X-OpenSRF-multipart'
32 MULTIPART_CONTENT_TYPE = 'multipart/x-mixed-replace;boundary="%s"'
33 JSON_CONTENT_TYPE = 'text/plain'
39 # If DEBUG_WRITE = True, all data sent to the client is also written
40 # to stderr (apache error log)
45 sys.stderr.write("%s\n\n" % str(msg))
50 ''' At time of writing, mod_python doesn't support a child_init handler,
51 so this function is called once per process to initialize
52 the opensrf connection '''
54 global INIT_COMPLETE, ROUTER_NAME, OSRF_DOMAIN
58 # Apache complains with: UnboundLocalError: local variable 'osrf' referenced before assignment
59 # if the following import line is removed, even though its also at the top of the file...
62 ops = req.get_options()
63 conf = ops['OSRF_CONFIG']
64 ctxt = ops.get('OSRF_CONFIG_CONTEXT') or 'opensrf'
65 osrf.system.System.net_connect(config_file=conf, config_context=ctxt)
67 ROUTER_NAME = osrf.conf.get('router_name')
68 OSRF_DOMAIN = osrf.conf.get('domain')
71 servers = ops.get('OSRF_CACHE_SERVERS')
73 servers = servers.split(',')
75 # no cache servers configured, see if we can talk to the settings server
77 servers = osrf.set.get('cache.global.servers.server')
78 if not isinstance(servers, list):
81 osrf.cache.CacheClient.connect(servers)
85 ''' Create the translator and tell it to process the request. '''
88 # capture the callback handle, clear it, then reset
89 # it after we've handled the request
90 handle = osrf.net.get_network_handle()
91 callback = handle.receive_callback
92 handle.set_receive_callback(None)
95 translator = HTTPTranslator(req)
96 status = translator.process()
97 osrf.log.log_debug("translator call resulted in status %d" % int(status))
98 if translator.local_xid:
101 handle.receive_callback = callback
105 class HTTPTranslator(object):
106 def __init__(self, apreq):
110 if OSRF_HTTP_HEADER_XID in apreq.headers_in:
111 osrf.log.log_debug('read XID from client %s' % apreq.headers_in.get(OSRF_HTTP_HEADER_XID))
112 osrf.log.set_xid(apreq.headers_in.get(OSRF_HTTP_HEADER_XID))
113 self.local_xid = False
116 osrf.log.log_debug('created new XID %s' % osrf.log.get_xid())
117 self.local_xid = True
119 if apreq.header_only:
122 for k,v in apreq.headers_in.iteritems():
123 osrf.log.log_internal('HEADER: %s = %s' % (k, v))
126 #post = util.parse_qsl(apreq.read(int(apreq.headers_in['Content-length'])))
127 post = util.parse_qsl(apreq.read())
128 osrf.log.log_debug('post = ' + str(post))
129 self.body = [d for d in post if d[0] == 'osrf-msg'][0][1]
130 osrf.log.log_debug(self.body)
132 osrf.log.log_warn("error parsing osrf message: %s" % unicode(e))
137 self.complete = False
138 self.handle = osrf.net.get_network_handle()
140 self.recipient = apreq.headers_in.get(OSRF_HTTP_HEADER_TO)
141 self.service = apreq.headers_in.get(OSRF_HTTP_HEADER_SERVICE)
142 self.thread = apreq.headers_in.get(OSRF_HTTP_HEADER_THREAD) or \
143 "%s%s" % (os.getpid(), time.time())
144 self.timeout = apreq.headers_in.get(OSRF_HTTP_HEADER_TIMEOUT) or 1200
145 self.multipart = str(
146 apreq.headers_in.get(OSRF_HTTP_HEADER_MULTIPART)).lower() == 'true'
147 self.connect_only = False
148 self.disconnect_only = False
150 # generate a random multipart delimiter
152 mpart.update("%f%d%d" % (time.time(), os.getpid(), \
153 random.randint(100, 10000000)))
154 self.delim = mpart.hexdigest()
155 self.remote_host = self.apreq.get_remote_host(apache.REMOTE_NOLOOKUP)
156 self.cache = osrf.cache.CacheClient()
162 if self.apreq.header_only:
165 return apache.HTTP_BAD_REQUEST
166 if not self.set_to_addr():
167 return apache.HTTP_BAD_REQUEST
168 if not self.parse_request():
169 return apache.HTTP_BAD_REQUEST
171 while self.handle.recv(0):
172 pass # drop stale messages
175 net_msg = osrf.net.NetworkMessage(
176 recipient=self.recipient, thread=self.thread, body=self.body)
177 self.handle.send(net_msg)
179 if self.disconnect_only:
180 osrf.log.log_debug("exiting early on DISCONNECT")
184 while not self.complete:
188 net_msg = self.handle.recv(self.timeout)
189 except osrf.net.XMPPNoRecipient:
190 return apache.HTTP_NOT_FOUND
193 return apache.GATEWAY_TIME_OUT
195 if not self.check_status(net_msg):
199 self.init_headers(net_msg)
203 self.respond_chunk(net_msg)
204 if self.connect_only:
207 self.messages.append(net_msg.body)
209 # condense the sets of arrays into a single array of messages
210 if self.complete or self.connect_only:
211 json = self.messages.pop(0)
212 while len(self.messages) > 0:
213 msg = self.messages.pop(0)
214 json = "%s,%s" % (json[0:len(json)-1], msg[1:])
216 self.write("%s" % json)
221 def parse_request(self):
223 If this is solely a DISCONNECT message, we set self.disconnect_only
225 @return True if the body parses correctly, False otherwise
227 osrf_msgs = osrf.json.to_object(self.body)
231 if len(osrf_msgs) == 1:
232 if osrf_msgs[0].type() == OSRF_MESSAGE_TYPE_CONNECT:
233 self.connect_only = True
234 elif osrf_msgs[0].type() == OSRF_MESSAGE_TYPE_DISCONNECT:
235 self.disconnect_only = True
240 def set_to_addr(self):
241 ''' Determines the TO address. Returns false if
242 the address is missing or ambiguous.
243 Also returns false if an explicit TO is specified and the
244 thread/IP/TO combination is not found in the session cache
248 osrf.log.log_warn("specifying both SERVICE and TO is not allowed")
250 self.recipient = "%s@%s/%s" % \
251 (ROUTER_NAME, OSRF_DOMAIN, self.service)
252 osrf.log.log_debug("set service to %s" % self.recipient)
256 # If the client specifies a specific TO address, verify it's
257 # the same address that was cached with the previous request.
258 obj = self.cache.get(self.thread)
259 if obj and obj['ip'] == self.remote_host and \
260 obj['jid'] == self.recipient:
262 osrf.log.log_warn("client [%s] attempted to send directly "
263 "[%s] without a session" % (self.remote_host, self.recipient))
267 def init_headers(self, net_msg):
268 osrf.log.log_debug("initializing request headers")
269 self.apreq.headers_out[OSRF_HTTP_HEADER_FROM] = net_msg.sender
270 self.apreq.headers_out[OSRF_HTTP_HEADER_THREAD] = self.thread
272 self.apreq.content_type = MULTIPART_CONTENT_TYPE % self.delim
273 self.write("--%s\n" % self.delim)
275 self.apreq.content_type = JSON_CONTENT_TYPE
276 self.cache.put(self.thread, \
277 {'ip':self.remote_host, 'jid': net_msg.sender}, CACHE_TIME)
279 osrf.log.log_debug("caching session [%s] for host [%s] and server "
280 " drone [%s]" % (self.thread, self.remote_host, net_msg.sender))
284 def check_status(self, net_msg):
285 ''' Checks the status of the server response.
286 If we received a timeout message, we drop it.
287 if it's any other non-continue status, we mark this session as
288 complete and carry on.
289 @return False if there is no data to return to the caller
290 (dropped message, eg. timeout), True otherwise '''
292 osrf_msgs = osrf.json.to_object(net_msg.body)
293 last_msg = osrf_msgs.pop()
295 if last_msg.type() == OSRF_MESSAGE_TYPE_STATUS:
296 code = int(last_msg.payload().statusCode())
297 osrf.log.log_debug("got a status message with code %d" % code)
299 if code == OSRF_STATUS_TIMEOUT:
300 osrf.log.log_debug("removing cached session [%s] and "
301 "dropping TIMEOUT message" % net_msg.thread)
302 self.cache.delete(net_msg.thread)
305 if code != OSRF_STATUS_CONTINUE:
311 def respond_chunk(self, resp):
312 ''' Writes a single multipart-delimited chunk of data '''
314 self.write("Content-type: %s\n\n" % JSON_CONTENT_TYPE)
315 self.write("%s\n\n" % resp.body)
317 self.write("--%s--\n" % self.delim)
319 self.write("--%s\n" % self.delim)
322 def write(self, msg):
323 ''' Writes data to the client stream. '''
326 sys.stderr.write(msg)
328 self.apreq.write(msg)