]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/python/osrf/http_translator.py
44ab7354b3eee21112885966388605550b26fae4
[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
100         if OSRF_HTTP_HEADER_XID in apreq.headers_in:
101             osrf.log.log_debug('read XID from client %s' % apreq.headers_in.get(OSRF_HTTP_HEADER_XID))
102             osrf.log.set_xid(apreq.headers_in.get(OSRF_HTTP_HEADER_XID))
103             self.local_xid = False
104         else:
105             osrf.log.make_xid()
106             osrf.log.log_debug('created new XID %s' % osrf.log.get_xid())
107             self.local_xid = True
108
109         if apreq.header_only: 
110             return
111
112         for k,v in apreq.headers_in.iteritems():
113             osrf.log.log_internal('HEADER: %s = %s' % (k, v))
114
115         try:
116             #post = util.parse_qsl(apreq.read(int(apreq.headers_in['Content-length'])))
117             post = util.parse_qsl(apreq.read())
118             osrf.log.log_debug('post = ' + str(post))
119             self.body = [d for d in post if d[0] == 'osrf-msg'][0][1]
120             osrf.log.log_debug(self.body)
121         except Exception, e: 
122             osrf.log.log_warn("error parsing osrf message: %s" % unicode(e))
123             self.body = None
124             return
125
126         self.messages = []
127         self.complete = False
128         self.handle = osrf.net.get_network_handle()
129         self.handle.set_receive_callback(None)
130
131         self.recipient = apreq.headers_in.get(OSRF_HTTP_HEADER_TO)
132         self.service = apreq.headers_in.get(OSRF_HTTP_HEADER_SERVICE)
133         self.thread = apreq.headers_in.get(OSRF_HTTP_HEADER_THREAD) or \
134             "%s%s" % (os.getpid(), time.time())
135         self.timeout = apreq.headers_in.get(OSRF_HTTP_HEADER_TIMEOUT) or 1200
136         self.multipart = str(
137             apreq.headers_in.get(OSRF_HTTP_HEADER_MULTIPART)).lower() == 'true'
138         self.connect_only = False
139         self.disconnect_only = False
140
141         # generate a random multipart delimiter
142         mpart = md5.new()
143         mpart.update("%f%d%d" % (time.time(), os.getpid(), \
144             random.randint(100, 10000000)))
145         self.delim = mpart.hexdigest()
146         self.remote_host = self.apreq.get_remote_host(apache.REMOTE_NOLOOKUP)
147         self.cache = osrf.cache.CacheClient()
148
149
150
151     def process(self):
152
153         if self.apreq.header_only: 
154             return apache.OK
155         if not self.body:
156             return apache.HTTP_BAD_REQUEST
157         if not self.set_to_addr():
158             return apache.HTTP_BAD_REQUEST
159         if not self.parse_request():
160             return apache.HTTP_BAD_REQUEST
161
162         while self.handle.recv(0):
163             pass # drop stale messages
164
165
166         net_msg = osrf.net.NetworkMessage(
167             recipient=self.recipient, thread=self.thread, body=self.body)
168         self.handle.send(net_msg)
169
170         if self.disconnect_only:
171             osrf.log.log_debug("exiting early on DISCONNECT")
172             return apache.OK
173
174         first_write = True
175         while not self.complete:
176
177             net_msg = None
178             try:
179                 net_msg = self.handle.recv(self.timeout)
180             except osrf.net.XMPPNoRecipient:
181                 return apache.HTTP_NOT_FOUND 
182
183             if not net_msg: 
184                 return apache.GATEWAY_TIME_OUT
185
186             if not self.check_status(net_msg):
187                 continue 
188
189             if first_write:
190                 self.init_headers(net_msg)
191                 first_write = False
192
193             if self.multipart:
194                 self.respond_chunk(net_msg)
195                 if self.connect_only:
196                     break
197             else:
198                 self.messages.append(net_msg.body)
199
200                 # condense the sets of arrays into a single array of messages
201                 if self.complete or self.connect_only:
202                     json = self.messages.pop(0)
203                     while len(self.messages) > 0:
204                         msg = self.messages.pop(0)
205                         json = "%s,%s" % (json[0:len(json)-1], msg[1:])
206                         
207                     self.write("%s" % json)
208
209
210         return apache.OK
211
212     def parse_request(self):
213         '''
214         If this is solely a DISCONNECT message, we set self.disconnect_only
215         to true
216         @return True if the body parses correctly, False otherwise
217         '''
218         osrf_msgs = osrf.json.to_object(self.body)
219         if not osrf_msgs:
220             return False
221         
222         if len(osrf_msgs) == 1:
223             if osrf_msgs[0].type() == OSRF_MESSAGE_TYPE_CONNECT:
224                 self.connect_only = True
225             elif osrf_msgs[0].type() == OSRF_MESSAGE_TYPE_DISCONNECT:
226                 self.disconnect_only = True
227
228         return True
229
230
231     def set_to_addr(self):
232         ''' Determines the TO address.  Returns false if 
233             the address is missing or ambiguous. 
234             Also returns false if an explicit TO is specified and the
235             thread/IP/TO combination is not found in the session cache
236             '''
237         if self.service:
238             if self.recipient:
239                 osrf.log.log_warn("specifying both SERVICE and TO is not allowed")
240                 return False
241             self.recipient = "%s@%s/%s" % \
242                 (ROUTER_NAME, OSRF_DOMAIN, self.service)
243             osrf.log.log_debug("set service to %s" % self.recipient)
244             return True
245         else:
246             if self.recipient:
247                 # If the client specifies a specific TO address, verify it's
248                 # the same address that was cached with the previous request.  
249                 obj = self.cache.get(self.thread)
250                 if obj and obj['ip'] == self.remote_host and \
251                     obj['jid'] == self.recipient:
252                     return True
253         osrf.log.log_warn("client [%s] attempted to send directly "
254             "[%s] without a session" % (self.remote_host, self.recipient))
255         return False
256
257         
258     def init_headers(self, net_msg):
259         osrf.log.log_debug("initializing request headers")
260         self.apreq.headers_out[OSRF_HTTP_HEADER_FROM] = net_msg.sender
261         self.apreq.headers_out[OSRF_HTTP_HEADER_THREAD] = self.thread
262         if self.multipart:
263             self.apreq.content_type = MULTIPART_CONTENT_TYPE % self.delim
264             self.write("--%s\n" % self.delim)
265         else:
266             self.apreq.content_type = JSON_CONTENT_TYPE
267         self.cache.put(self.thread, \
268             {'ip':self.remote_host, 'jid': net_msg.sender}, CACHE_TIME)
269
270         osrf.log.log_debug("caching session [%s] for host [%s] and server "
271             " drone [%s]" % (self.thread, self.remote_host, net_msg.sender))
272
273
274
275     def check_status(self, net_msg): 
276         ''' Checks the status of the server response. 
277             If we received a timeout message, we drop it.
278             if it's any other non-continue status, we mark this session as
279             complete and carry on.
280             @return False if there is no data to return to the caller 
281             (dropped message, eg. timeout), True otherwise '''
282
283         osrf.log.log_debug('checking status...')
284         osrf_msgs = osrf.json.to_object(net_msg.body)
285         last_msg = osrf_msgs.pop()
286
287         if last_msg.type() == OSRF_MESSAGE_TYPE_STATUS:
288             code = int(last_msg.payload().statusCode())
289             osrf.log.log_debug("got a status message with code %d" % code)
290
291             if code == OSRF_STATUS_TIMEOUT:
292                 osrf.log.log_debug("removing cached session [%s] and "
293                     "dropping TIMEOUT message" % net_msg.thread)
294                 self.cache.delete(net_msg.thread)
295                 return False 
296
297             if code != OSRF_STATUS_CONTINUE:
298                 self.complete = True
299
300         return True
301
302
303     def respond_chunk(self, resp):
304         ''' Writes a single multipart-delimited chunk of data '''
305
306         self.write("Content-type: %s\n\n" % JSON_CONTENT_TYPE)
307         self.write("%s\n\n" % resp.body)
308         if self.complete:
309             self.write("--%s--\n" % self.delim)
310         else:
311             self.write("--%s\n" % self.delim)
312         self.apreq.flush()
313
314     def write(self, msg):
315         ''' Writes data to the client stream. '''
316
317         if DEBUG_WRITE:
318             sys.stderr.write(msg)
319             sys.stderr.flush()
320         self.apreq.write(msg)
321             
322