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