]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/python/osrf/http_translator.py
3a4966b73a37742a101b73bfb6034495df6d240d
[OpenSRF.git] / src / python / osrf / http_translator.py
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
6
7
8 ''' 
9 Proof of concept OpenSRF-HTTP multipart streaming gateway.
10
11 Example Apache mod_python config:
12
13 <Location /osrf-http-translator>
14    SetHandler mod_python
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
20    # testing only
21    PythonAutoReload On
22 </Location>
23 '''
24
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'
34 CACHE_TIME = 300
35
36 ROUTER_NAME = None
37 OSRF_DOMAIN = None
38
39 # If DEBUG_WRITE = True, all data sent to the client is also written
40 # to stderr (apache error log)
41 DEBUG_WRITE = False
42
43 def _dbg(msg):
44     ''' testing only '''
45     sys.stderr.write("%s\n\n" % str(msg))
46     sys.stderr.flush()
47
48
49 INIT_COMPLETE = False
50 def child_init(req):
51     ''' At time of writing, mod_python doesn't support a child_init handler,
52         so this function is called once per process to initialize 
53         the opensrf connection '''
54
55     global INIT_COMPLETE, ROUTER_NAME, OSRF_DOMAIN
56     if INIT_COMPLETE: 
57         return
58
59     # Apache complains with: UnboundLocalError: local variable 'osrf' referenced before assignment
60     # if the following import line is removed, even though its also at the top of the file...
61     import osrf.system 
62
63     ops = req.get_options()
64     conf = ops['OSRF_CONFIG']
65     ctxt = ops.get('OSRF_CONFIG_CONTEXT') or 'opensrf'
66     osrf.system.System.net_connect(config_file=conf, config_context=ctxt)
67
68     ROUTER_NAME = osrf.conf.get('router_name')
69     OSRF_DOMAIN = osrf.conf.get('domain')
70     INIT_COMPLETE = True
71
72     servers = ops.get('OSRF_CACHE_SERVERS')
73     if servers:
74         servers = servers.split(',')
75     else:
76         # no cache servers configured, see if we can talk to the settings server
77         import osrf.set
78         servers = osrf.set.get('cache.global.servers.server')
79         if not isinstance(servers, list):
80             servers = [servers]
81
82     osrf.cache.CacheClient.connect(servers)
83
84
85 def handler(req):
86     ''' Create the translator and tell it to process the request. '''
87     child_init(req)
88     translator = HTTPTranslator(req)
89     status = translator.process()
90     osrf.log.log_debug("translator call resulted in status %d" % int(status))
91     if translator.local_xid:
92         osrf.log.clear_xid()
93     return status
94
95 class HTTPTranslator(object):
96     def __init__(self, apreq):
97
98         self.apreq = apreq
99         if apreq.header_only: 
100             return
101
102         for k,v in apreq.headers_in.iteritems():
103             osrf.log.log_internal('HEADER: %s = %s' % (k, v))
104
105         try:
106             post = util.parse_qsl(apreq.read(int(apreq.headers_in['Content-length'])))
107             osrf.log.log_debug('post = ' + str(post))
108             self.body = [d for d in post if d[0] == 'osrf-msg'][0][1]
109             osrf.log.log_debug(self.body)
110         except Exception, e: 
111             osrf.log.log_warn("error parsing osrf message: %s" % unicode(e))
112             self.body = None
113             return
114
115         self.messages = []
116         self.complete = False
117         self.handle = osrf.net.get_network_handle()
118         self.handle.set_receive_callback(None)
119
120         self.recipient = apreq.headers_in.get(OSRF_HTTP_HEADER_TO)
121         self.service = apreq.headers_in.get(OSRF_HTTP_HEADER_SERVICE)
122         self.thread = apreq.headers_in.get(OSRF_HTTP_HEADER_THREAD) or \
123             "%s%s" % (os.getpid(), time.time())
124         self.timeout = apreq.headers_in.get(OSRF_HTTP_HEADER_TIMEOUT) or 1200
125         self.multipart = str(
126             apreq.headers_in.get(OSRF_HTTP_HEADER_MULTIPART)).lower() == 'true'
127         self.connect_only = False
128         self.disconnect_only = False
129
130         # generate a random multipart delimiter
131         mpart = md5.new()
132         mpart.update("%f%d%d" % (time.time(), os.getpid(), \
133             random.randint(100, 10000000)))
134         self.delim = mpart.hexdigest()
135         self.remote_host = self.apreq.get_remote_host(apache.REMOTE_NOLOOKUP)
136         self.cache = osrf.cache.CacheClient()
137
138         if OSRF_HTTP_HEADER_XID in apreq.headers_in:
139             osrf.log.log_debug('read XID from client %s' % apreq.headers_in.get(OSRF_HTTP_HEADER_XID))
140             osrf.log.set_xid(apreq.headers_in.get(OSRF_HTTP_HEADER_XID))
141             self.local_xid = False
142         else:
143             osrf.log.make_xid()
144             osrf.log.log_debug('created new XID %s' % osrf.log.get_xid())
145             self.local_xid = True
146
147
148     def process(self):
149
150         if self.apreq.header_only: 
151             return apache.OK
152         if not self.body:
153             return apache.HTTP_BAD_REQUEST
154         if not self.set_to_addr():
155             return apache.HTTP_BAD_REQUEST
156         if not self.parse_request():
157             return apache.HTTP_BAD_REQUEST
158
159         while self.handle.recv(0):
160             pass # drop stale messages
161
162
163         net_msg = osrf.net.NetworkMessage(
164             recipient=self.recipient, thread=self.thread, body=self.body)
165         self.handle.send(net_msg)
166
167         if self.disconnect_only:
168             osrf.log.log_debug("exiting early on DISCONNECT")
169             return apache.OK
170
171         first_write = True
172         while not self.complete:
173
174             net_msg = None
175             try:
176                 net_msg = self.handle.recv(self.timeout)
177             except osrf.net.XMPPNoRecipient:
178                 return apache.HTTP_NOT_FOUND 
179
180             if not net_msg: 
181                 return apache.GATEWAY_TIME_OUT
182
183             if not self.check_status(net_msg):
184                 continue 
185
186             if first_write:
187                 self.init_headers(net_msg)
188                 first_write = False
189
190             if self.multipart:
191                 self.respond_chunk(net_msg)
192                 if self.connect_only:
193                     break
194             else:
195                 self.messages.append(net_msg.body)
196
197                 # condense the sets of arrays into a single array of messages
198                 if self.complete or self.connect_only:
199                     json = self.messages.pop(0)
200                     while len(self.messages) > 0:
201                         msg = self.messages.pop(0)
202                         json = "%s,%s" % (json[0:len(json)-1], msg[1:])
203                         
204                     self.write("%s" % json)
205
206
207         return apache.OK
208
209     def parse_request(self):
210         '''
211         If this is solely a DISCONNECT message, we set self.disconnect_only
212         to true
213         @return True if the body parses correctly, False otherwise
214         '''
215         osrf_msgs = osrf.json.to_object(self.body)
216         if not osrf_msgs:
217             return False
218         
219         if len(osrf_msgs) == 1:
220             if osrf_msgs[0].type() == OSRF_MESSAGE_TYPE_CONNECT:
221                 self.connect_only = True
222             elif osrf_msgs[0].type() == OSRF_MESSAGE_TYPE_DISCONNECT:
223                 self.disconnect_only = True
224
225         return True
226
227
228     def set_to_addr(self):
229         ''' Determines the TO address.  Returns false if 
230             the address is missing or ambiguous. 
231             Also returns false if an explicit TO is specified and the
232             thread/IP/TO combination is not found in the session cache
233             '''
234         if self.service:
235             if self.recipient:
236                 osrf.log.log_warn("specifying both SERVICE and TO is not allowed")
237                 return False
238             self.recipient = "%s@%s/%s" % \
239                 (ROUTER_NAME, OSRF_DOMAIN, self.service)
240             osrf.log.log_debug("set service to %s" % self.recipient)
241             return True
242         else:
243             if self.recipient:
244                 # If the client specifies a specific TO address, verify it's
245                 # the same address that was cached with the previous request.  
246                 obj = self.cache.get(self.thread)
247                 if obj and obj['ip'] == self.remote_host and \
248                     obj['jid'] == self.recipient:
249                     return True
250         osrf.log.log_warn("client [%s] attempted to send directly "
251             "[%s] without a session" % (self.remote_host, self.recipient))
252         return False
253
254         
255     def init_headers(self, net_msg):
256         osrf.log.log_debug("initializing request headers")
257         self.apreq.headers_out[OSRF_HTTP_HEADER_FROM] = net_msg.sender
258         self.apreq.headers_out[OSRF_HTTP_HEADER_THREAD] = self.thread
259         if self.multipart:
260             self.apreq.content_type = MULTIPART_CONTENT_TYPE % self.delim
261             self.write("--%s\n" % self.delim)
262         else:
263             self.apreq.content_type = JSON_CONTENT_TYPE
264         self.cache.put(self.thread, \
265             {'ip':self.remote_host, 'jid': net_msg.sender}, CACHE_TIME)
266
267         osrf.log.log_debug("caching session [%s] for host [%s] and server "
268             " drone [%s]" % (self.thread, self.remote_host, net_msg.sender))
269
270
271
272     def check_status(self, net_msg): 
273         ''' Checks the status of the server response. 
274             If we received a timeout message, we drop it.
275             if it's any other non-continue status, we mark this session as
276             complete and carry on.
277             @return False if there is no data to return to the caller 
278             (dropped message, eg. timeout), True otherwise '''
279
280         osrf.log.log_debug('checking status...')
281         osrf_msgs = osrf.json.to_object(net_msg.body)
282         last_msg = osrf_msgs.pop()
283
284         if last_msg.type() == OSRF_MESSAGE_TYPE_STATUS:
285             code = int(last_msg.payload().statusCode())
286             osrf.log.log_debug("got a status message with code %d" % code)
287
288             if code == OSRF_STATUS_TIMEOUT:
289                 osrf.log.log_debug("removing cached session [%s] and "
290                     "dropping TIMEOUT message" % net_msg.thread)
291                 self.cache.delete(net_msg.thread)
292                 return False 
293
294             if code != OSRF_STATUS_CONTINUE:
295                 self.complete = True
296
297         return True
298
299
300     def respond_chunk(self, resp):
301         ''' Writes a single multipart-delimited chunk of data '''
302
303         self.write("Content-type: %s\n\n" % JSON_CONTENT_TYPE)
304         self.write("%s\n\n" % resp.body)
305         if self.complete:
306             self.write("--%s--\n" % self.delim)
307         else:
308             self.write("--%s\n" % self.delim)
309         self.apreq.flush()
310
311     def write(self, msg):
312         ''' Writes data to the client stream. '''
313
314         if DEBUG_WRITE:
315             sys.stderr.write(msg)
316             sys.stderr.flush()
317         self.apreq.write(msg)
318             
319