]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/python/osrf/ses.py
Add some basic locale support.
[OpenSRF.git] / src / python / osrf / ses.py
1 # -----------------------------------------------------------------------
2 # Copyright (C) 2007  Georgia Public Library Service
3 # Bill Erickson <billserickson@gmail.com>
4
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 # -----------------------------------------------------------------------
15
16 import osrf.json
17 import osrf.conf
18 import osrf.log
19 import osrf.net
20 import osrf.net_obj
21 from osrf.const import OSRF_APP_SESSION_CONNECTED, \
22     OSRF_APP_SESSION_CONNECTING, OSRF_APP_SESSION_DISCONNECTED, \
23     OSRF_MESSAGE_TYPE_CONNECT, OSRF_MESSAGE_TYPE_DISCONNECT, \
24     OSRF_MESSAGE_TYPE_REQUEST
25 import osrf.ex
26 import random, os, time, threading
27
28
29 # -----------------------------------------------------------------------
30 # Go ahead and register the common network objects
31 # -----------------------------------------------------------------------
32 osrf.net_obj.NetworkRegisterHint('osrfMessage', ['threadTrace', 'locale', 'type', 'payload'], 'hash')
33 osrf.net_obj.NetworkRegisterHint('osrfMethod', ['method', 'params'], 'hash')
34 osrf.net_obj.NetworkRegisterHint('osrfResult', ['status', 'statusCode', 'content'], 'hash')
35 osrf.net_obj.NetworkRegisterHint('osrfConnectStatus', ['status', 'statusCode'], 'hash')
36 osrf.net_obj.NetworkRegisterHint('osrfMethodException', ['status', 'statusCode'], 'hash')
37
38
39 class Session(object):
40     """Abstract session superclass."""
41
42     ''' Global cache of in-service sessions '''
43     session_cache = {}
44
45     def __init__(self):
46         # by default, we're connected to no one
47         self.state = OSRF_APP_SESSION_DISCONNECTED
48         self.remote_id = None
49         self.locale = None
50
51     def find_session(threadTrace):
52         return Session.session_cache.get(threadTrace)
53     find_session = staticmethod(find_session)
54
55     def wait(self, timeout=120):
56         """Wait up to <timeout> seconds for data to arrive on the network"""
57         osrf.log.log_internal("Session.wait(%d)" % timeout)
58         handle = osrf.net.get_network_handle()
59         handle.recv(timeout)
60
61     def send(self, omessage):
62         """Sends an OpenSRF message"""
63         net_msg = osrf.net.NetworkMessage(
64             recipient      = self.remote_id,
65             body    = osrf.json.to_json([omessage]),
66             thread = self.thread,
67             locale = self.locale,
68         )
69
70         handle = osrf.net.get_network_handle()
71         handle.send(net_msg)
72
73     def cleanup(self):
74         """Removes the session from the global session cache."""
75         del Session.session_cache[self.thread]
76
77 class ClientSession(Session):
78     """Client session object.  Use this to make server requests."""
79
80     def __init__(self, service):
81         
82         # call superclass constructor
83         Session.__init__(self)
84
85         # the remote service we want to make requests of
86         self.service = service
87
88         # find the remote service handle <router>@<domain>/<service>
89         domain = osrf.conf.get('domains.domain', 0)
90         router = osrf.conf.get('router_name')
91         self.remote_id = "%s@%s/%s" % (router, domain, service)
92         self.orig_remote_id = self.remote_id
93
94         # generate a random message thread
95         self.thread = "%s%s%s%s" % (os.getpid(), 
96             str(random.randint(100,100000)), str(time.time()),threading.currentThread().getName().lower())
97
98         # how many requests this session has taken part in
99         self.next_id = 0 
100
101         # cache of request objects 
102         self.requests = {}
103
104         # cache this session in the global session cache
105         Session.session_cache[self.thread] = self
106
107     def reset_request_timeout(self, rid):
108         req = self.find_request(rid)
109         if req:
110             req.reset_timeout = True
111             
112
113     def request2(self, method, arr):
114         """Creates a new request and sends the request to the server using a python array as the params."""
115         return self.__request(method, arr)
116
117     def request(self, method, *args):
118         """Creates a new request and sends the request to the server using a variable argument list as params"""
119         arr = list(args)
120         return self.__request(method, arr)
121
122     def __request(self, method, arr):
123         """Builds the request object and sends it."""
124         if self.state != OSRF_APP_SESSION_CONNECTED:
125             self.reset_remote_id()
126
127         osrf.log.logDebug("Sending request %s -> %s " % (self.service, method))
128         req = Request(self, self.next_id, method, arr)
129         self.requests[str(self.next_id)] = req
130         self.next_id += 1
131         req.send()
132         return req
133
134
135     def connect(self, timeout=10):
136         """Connects to a remote service"""
137
138         if self.state == OSRF_APP_SESSION_CONNECTED:
139             return True
140         self.state == OSRF_APP_SESSION_CONNECTING
141
142         # construct and send a CONNECT message
143         self.send(
144             osrf.net_obj.NetworkObject.osrfMessage( 
145                 {   'threadTrace' : 0,
146                     'type' : OSRF_MESSAGE_TYPE_CONNECT
147                 } 
148             )
149         )
150
151         while timeout >= 0 and not self.state == OSRF_APP_SESSION_CONNECTED:
152             start = time.time()
153             self.wait(timeout)
154             timeout -= time.time() - start
155         
156         if self.state != OSRF_APP_SESSION_CONNECTED:
157             raise osrf.ex.OSRFServiceException("Unable to connect to " + self.service)
158         
159         return True
160
161     def disconnect(self):
162         """Disconnects from a remote service"""
163
164         if self.state == OSRF_APP_SESSION_DISCONNECTED:
165             return True
166
167         self.send(
168             osrf.net_obj.NetworkObject.osrfMessage( 
169                 {   'threadTrace' : 0,
170                     'type' : OSRF_MESSAGE_TYPE_DISCONNECT
171                 } 
172             )
173         )
174
175         self.state = OSRF_APP_SESSION_DISCONNECTED
176
177     
178     def set_remote_id(self, remoteid):
179         self.remote_id = remoteid
180         osrf.log.log_internal("Setting request remote ID to %s" % self.remote_id)
181
182     def reset_remote_id(self):
183         """Recovers the original remote id"""
184         self.remote_id = self.orig_remote_id
185         osrf.log.log_internal("Resetting remote ID to %s" % self.remote_id)
186
187     def push_response_queue(self, message):
188         """Pushes the message payload onto the response queue 
189             for the request associated with the message's ID."""
190         osrf.log.logDebug("pushing %s" % message.payload())
191         try:
192             self.find_request(message.threadTrace()).pushResponse(message.payload())
193         except Exception, e: 
194             osrf.log.log_warn("pushing respond to non-existent request %s : %s" % (message.threadTrace(), e))
195
196     def find_request(self, rid):
197         """Returns the original request matching this message's threadTrace."""
198         try:
199             return self.requests[str(rid)]
200         except KeyError:
201             osrf.log.logDebug('find_request(): non-existent request %s' % str(rid))
202             return None
203
204
205
206 class Request(object):
207     """Represents a single OpenSRF request.
208         A request is made and any resulting respones are 
209         collected for the client."""
210
211     def __init__(self, session, rid, method=None, params=[], locale='en-US'):
212
213         self.session = session # my session handle
214         self.rid     = rid # my unique request ID
215         self.method = method # method name
216         self.params = params # my method params
217         self.queue  = [] # response queue
218         self.reset_timeout = False # resets the recv timeout?
219         self.complete = False # has the server told us this request is done?
220         self.send_time = 0 # local time the request was put on the wire
221         self.complete_time =  0 # time the server told us the request was completed
222         self.first_response_time = 0 # time it took for our first reponse to be received
223         self.locale = locale
224
225     def send(self):
226         """Sends a request message"""
227
228         # construct the method object message with params and method name
229         method = osrf.net_obj.NetworkObject.osrfMethod( {
230             'method' : self.method,
231             'params' : self.params
232         } )
233
234         # construct the osrf message with our method message embedded
235         message = osrf.net_obj.NetworkObject.osrfMessage( {
236             'threadTrace' : self.rid,
237             'type' : OSRF_MESSAGE_TYPE_REQUEST,
238             'payload' : method,
239             'locale' : self.locale
240         } )
241
242         self.send_time = time.time()
243         self.session.send(message)
244
245     def recv(self, timeout=120):
246         """Waits up to <timeout> seconds for a response to this request.
247         
248             If a message is received in time, the response message is returned.
249             Returns None otherwise."""
250
251         self.session.wait(0)
252
253         orig_timeout = timeout
254         while not self.complete and timeout >= 0 and len(self.queue) == 0:
255             s = time.time()
256             self.session.wait(timeout)
257             timeout -= time.time() - s
258             if self.reset_timeout:
259                 self.reset_timeout = False
260                 timeout = orig_timeout
261
262         now = time.time()
263
264         # -----------------------------------------------------------------
265         # log some statistics 
266         if len(self.queue) > 0:
267             if not self.first_response_time:
268                 self.first_response_time = now
269                 osrf.log.logDebug("time elapsed before first response: %f" \
270                     % (self.first_response_time - self.send_time))
271
272         if self.complete:
273             if not self.complete_time:
274                 self.complete_time = now
275                 osrf.log.logDebug("time elapsed before complete: %f" \
276                     % (self.complete_time - self.send_time))
277         # -----------------------------------------------------------------
278
279
280         if len(self.queue) > 0:
281             # we have a reponse, return it
282             return self.queue.pop(0)
283
284         return None
285
286     def pushResponse(self, content):
287         """Pushes a method response onto this requests response queue."""
288         self.queue.append(content)
289
290     def cleanup(self):
291         """Cleans up request data from the cache. 
292
293             Do this when you are done with a request to prevent "leaked" cache memory."""
294         del self.session.requests[str(self.rid)]
295
296     def set_complete(self):
297         """Sets me as complete.  This means the server has sent a 'request complete' message"""
298         self.complete = True
299
300
301 class ServerSession(Session):
302     """Implements a server-side session"""
303     pass
304
305
306 def AtomicRequest(service, method, *args):
307     ses = ClientSession(service)
308     req = ses.request2(method, list(args))
309     resp = req.recv()
310     data = resp.content()
311     req.cleanup()
312     ses.cleanup()
313     return data
314
315
316