]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/libstack/osrf_app_session.c
e3bfe5cbafaa323570933869962bd11fd6557384
[OpenSRF.git] / src / libstack / osrf_app_session.c
1 #include "osrf_app_session.h"
2 #include <time.h>
3
4 /* the global app_session cache */
5 osrfHash* osrfAppSessionCache = NULL;
6
7
8 // --------------------------------------------------------------------------
9 // --------------------------------------------------------------------------
10 // Request API
11 // --------------------------------------------------------------------------
12
13 /** Allocation and initializes a new app_request object */
14 osrf_app_request* _osrf_app_request_init( 
15                 osrf_app_session* session, osrf_message* msg ) {
16
17         osrf_app_request* req = 
18                 (osrf_app_request*) safe_malloc(sizeof(osrf_app_request));
19
20         req->session            = session;
21         req->request_id = msg->thread_trace;
22         req->complete           = 0;
23         req->payload            = msg;
24         req->result                     = NULL;
25
26         return req;
27
28 }
29
30
31 void osrfAppSessionCleanup() {
32         osrfHashFree(osrfAppSessionCache);      
33 }
34
35
36
37 /** Frees memory used by an app_request object */
38 void _osrf_app_request_free( void * req ){
39         if( req == NULL ) return;
40         osrfAppRequest* r = (osrfAppRequest*) req;
41         if( r->payload ) osrf_message_free( r->payload );
42         free( r );
43 }
44
45 /** Pushes the given message onto the list of 'responses' to this request */
46 void _osrf_app_request_push_queue( osrf_app_request* req, osrf_message* result ){
47         if(req == NULL || result == NULL) return;
48         osrfLogDebug( OSRF_LOG_MARK,  "App Session pushing request [%d] onto request queue", result->thread_trace );
49         if(req->result == NULL) {
50                 req->result = result;
51
52         } else {
53                 
54                 osrf_message* ptr = req->result;
55                 osrf_message* ptr2 = req->result->next;
56                 while( ptr2 ) {
57                         ptr = ptr2;
58                         ptr2 = ptr2->next;
59                 }
60                 ptr->next = result;
61         }
62 }
63
64 /** Removes this app_request from our session request set */
65 void osrf_app_session_request_finish( 
66                 osrf_app_session* session, int req_id ){
67
68         if(session == NULL) return;
69         osrf_app_request* req = OSRF_LIST_GET_INDEX( session->request_queue, req_id );
70         if(req == NULL) return;
71         osrfListRemove( req->session->request_queue, req->request_id );
72 }
73
74
75 void osrf_app_session_request_reset_timeout( osrf_app_session* session, int req_id ) {
76         if(session == NULL) return;
77         osrfLogDebug( OSRF_LOG_MARK, "Resetting request timeout %d", req_id );
78         osrf_app_request* req = OSRF_LIST_GET_INDEX( session->request_queue, req_id );
79         if(req == NULL) return;
80         req->reset_timeout = 1;
81 }
82
83 /** Checks the receive queue for messages.  If any are found, the first
84   * is popped off and returned.  Otherwise, this method will wait at most timeout 
85   * seconds for a message to appear in the receive queue.  Once it arrives it is returned.
86   * If no messages arrive in the timeout provided, null is returned.
87   */
88 osrf_message* _osrf_app_request_recv( osrf_app_request* req, int timeout ) {
89
90         if(req == NULL) return NULL;
91
92         if( req->result != NULL ) {
93                 /* pop off the first message in the list */
94                 osrf_message* tmp_msg = req->result;
95                 req->result = req->result->next;
96                 return tmp_msg;
97         }
98
99         time_t start = time(NULL);      
100         time_t remaining = (time_t) timeout;
101
102         while( remaining >= 0 ) {
103                 /* tell the session to wait for stuff */
104                 osrfLogDebug( OSRF_LOG_MARK,  "In app_request receive with remaining time [%d]", (int) remaining );
105
106                 osrf_app_session_queue_wait( req->session, 0, NULL );
107
108                 if( req->result != NULL ) { /* if we received anything */
109                         /* pop off the first message in the list */
110                         osrfLogDebug( OSRF_LOG_MARK,  "app_request_recv received a message, returning it");
111                         osrf_message* ret_msg = req->result;
112                         osrf_message* tmp_msg = ret_msg->next;
113                         req->result = tmp_msg;
114                         return ret_msg;
115                 }
116
117                 if( req->complete )
118                         return NULL;
119
120                 osrf_app_session_queue_wait( req->session, (int) remaining, NULL );
121
122                 if( req->result != NULL ) { /* if we received anything */
123                         /* pop off the first message in the list */
124                         osrfLogDebug( OSRF_LOG_MARK,  "app_request_recv received a message, returning it");
125                         osrf_message* ret_msg = req->result;
126                         osrf_message* tmp_msg = ret_msg->next;
127                         req->result = tmp_msg;
128                         return ret_msg;
129                 }
130                 if( req->complete )
131                         return NULL;
132
133                 if(req->reset_timeout) {
134                         remaining = (time_t) timeout;
135                         req->reset_timeout = 0;
136                         osrfLogDebug( OSRF_LOG_MARK, "Recevied a timeout reset");
137                 } else {
138                         remaining -= (int) (time(NULL) - start);
139                 }
140         }
141
142         osrfLogInfo( OSRF_LOG_MARK, "Returning NULL from app_request_recv after timeout");
143         return NULL;
144 }
145
146 /** Resend this requests original request message */
147 int _osrf_app_request_resend( osrf_app_request* req ) {
148         if(req == NULL) return 0;
149         if(!req->complete) {
150                 osrfLogDebug( OSRF_LOG_MARK,  "Resending request [%d]", req->request_id );
151                 return _osrf_app_session_send( req->session, req->payload );
152         }
153         return 1;
154 }
155
156
157
158 // --------------------------------------------------------------------------
159 // --------------------------------------------------------------------------
160 // Session API
161 // --------------------------------------------------------------------------
162
163 /** returns a session from the global session hash */
164 osrf_app_session* osrf_app_session_find_session( char* session_id ) {
165         if(session_id) return osrfHashGet(osrfAppSessionCache, session_id);
166         return NULL;
167 }
168
169
170 /** adds a session to the global session cache */
171 void _osrf_app_session_push_session( osrf_app_session* session ) {
172         if(!session) return;
173         if( osrfAppSessionCache == NULL ) osrfAppSessionCache = osrfNewHash();
174         if( osrfHashGet( osrfAppSessionCache, session->session_id ) ) return;
175         osrfHashSet( osrfAppSessionCache, session, session->session_id );
176 }
177
178 /** Allocates a initializes a new app_session */
179
180 osrf_app_session* osrfAppSessionClientInit( char* remote_service ) {
181         return osrf_app_client_session_init( remote_service );
182 }
183
184 osrf_app_session* osrf_app_client_session_init( char* remote_service ) {
185
186         osrf_app_session* session = safe_malloc(sizeof(osrf_app_session));      
187
188         session->transport_handle = osrf_system_get_transport_client();
189         if( session->transport_handle == NULL ) {
190                 osrfLogWarning( OSRF_LOG_MARK, "No transport client for service 'client'");
191                 return NULL;
192         }
193
194         char target_buf[512];
195         memset(target_buf,0,512);
196
197         osrfStringArray* arr = osrfNewStringArray(8);
198         osrfConfigGetValueList(NULL, arr, "/domains/domain");
199         char* domain = osrfStringArrayGetString(arr, 0);
200         char* router_name = osrfConfigGetValue(NULL, "/router_name");
201         
202         sprintf( target_buf, "%s@%s/%s",  router_name, domain, remote_service );
203         osrfStringArrayFree(arr);
204         //free(domain);
205         free(router_name);
206
207         session->request_queue = osrfNewList();
208         session->request_queue->freeItem = &_osrf_app_request_free;
209         session->remote_id = strdup(target_buf);
210         session->orig_remote_id = strdup(session->remote_id);
211         session->remote_service = strdup(remote_service);
212
213         #ifdef ASSUME_STATELESS
214         session->stateless = 1;
215         osrfLogDebug( OSRF_LOG_MARK, "%s session is stateless", remote_service );
216         #else
217         session->stateless = 0;
218         osrfLogDebug( OSRF_LOG_MARK, "%s session is NOT stateless", remote_service );
219         #endif
220
221         /* build a chunky, random session id */
222         char id[256];
223         memset(id,0,256);
224
225         sprintf(id, "%lf.%d%d", get_timestamp_millis(), (int)time(NULL), getpid());
226         session->session_id = strdup(id);
227         osrfLogDebug( OSRF_LOG_MARK,  "Building a new client session with id [%s] [%s]", 
228                         session->remote_service, session->session_id );
229
230         session->thread_trace = 0;
231         session->state = OSRF_SESSION_DISCONNECTED;
232         session->type = OSRF_SESSION_CLIENT;
233         //session->next = NULL;
234         _osrf_app_session_push_session( session );
235         return session;
236 }
237
238 osrf_app_session* osrf_app_server_session_init( 
239                 char* session_id, char* our_app, char* remote_id ) {
240
241         osrfLogDebug( OSRF_LOG_MARK, "Initing server session with session id %s, service %s,"
242                         " and remote_id %s", session_id, our_app, remote_id );
243
244         osrf_app_session* session = osrf_app_session_find_session( session_id );
245         if(session) return session;
246
247         session = safe_malloc(sizeof(osrf_app_session));        
248
249         session->transport_handle = osrf_system_get_transport_client();
250         if( session->transport_handle == NULL ) {
251                 osrfLogWarning( OSRF_LOG_MARK, "No transport client for service '%s'", our_app );
252                 return NULL;
253         }
254
255         int stateless = 0;
256         char* statel = osrf_settings_host_value("/apps/%s/stateless", our_app );
257         if(statel) stateless = atoi(statel);
258         free(statel);
259
260
261         session->request_queue = osrfNewList();
262         session->request_queue->freeItem = &_osrf_app_request_free;
263         session->remote_id = strdup(remote_id);
264         session->orig_remote_id = strdup(remote_id);
265         session->session_id = strdup(session_id);
266         session->remote_service = strdup(our_app);
267         session->stateless = stateless;
268
269         #ifdef ASSUME_STATELESS
270         session->stateless = 1;
271         #endif
272
273         session->thread_trace = 0;
274         session->state = OSRF_SESSION_DISCONNECTED;
275         session->type = OSRF_SESSION_SERVER;
276
277         _osrf_app_session_push_session( session );
278         return session;
279
280 }
281
282
283
284 /** frees memory held by a session */
285 void _osrf_app_session_free( osrf_app_session* session ){
286         if(session==NULL)
287                 return;
288
289         if( session->userDataFree && session->userData ) 
290                 session->userDataFree(session->userData);
291         
292         free(session->remote_id);
293         free(session->orig_remote_id);
294         free(session->session_id);
295         free(session->remote_service);
296         osrfListFree(session->request_queue);
297         free(session);
298 }
299
300 int osrfAppSessionMakeRequest(
301                 osrf_app_session* session, jsonObject* params, 
302                 char* method_name, int protocol, string_array* param_strings ) {
303
304         return osrf_app_session_make_req( session, params, 
305                         method_name, protocol, param_strings );
306 }
307
308 int osrf_app_session_make_req( 
309                 osrf_app_session* session, jsonObject* params, 
310                 char* method_name, int protocol, string_array* param_strings ) {
311         if(session == NULL) return -1;
312
313    osrfLogMkXid();
314
315         osrf_message* req_msg = osrf_message_init( REQUEST, ++(session->thread_trace), protocol );
316         osrf_message_set_method(req_msg, method_name);
317         if(params) {
318                 osrf_message_set_params(req_msg, params);
319
320         } else {
321
322                 if(param_strings) {
323                         int i;
324                         for(i = 0; i!= param_strings->size ; i++ ) {
325                                 osrf_message_add_param(req_msg,
326                                         string_array_get_string(param_strings,i));
327                         }
328                 }
329         }
330
331         osrf_app_request* req = _osrf_app_request_init( session, req_msg );
332         if(_osrf_app_session_send( session, req_msg ) ) {
333                 osrfLogWarning( OSRF_LOG_MARK,  "Error sending request message [%d]", session->thread_trace );
334                 return -1;
335         }
336
337         osrfLogDebug( OSRF_LOG_MARK,  "Pushing [%d] onto requeust queue for session [%s] [%s]",
338                         req->request_id, session->remote_service, session->session_id );
339         osrfListSet( session->request_queue, req, req->request_id ); 
340         return req->request_id;
341 }
342
343 void osrf_app_session_set_complete( osrf_app_session* session, int request_id ) {
344         if(session == NULL)
345                 return;
346
347         osrf_app_request* req = OSRF_LIST_GET_INDEX( session->request_queue, request_id );
348         if(req) req->complete = 1;
349 }
350
351 int osrf_app_session_request_complete( osrf_app_session* session, int request_id ) {
352         if(session == NULL)
353                 return 0;
354         osrf_app_request* req = OSRF_LIST_GET_INDEX( session->request_queue, request_id );
355         if(req)
356                 return req->complete;
357         return 0;
358 }
359
360
361 /** Resets the remote connection id to that of the original*/
362 void osrf_app_session_reset_remote( osrf_app_session* session ){
363         if( session==NULL )
364                 return;
365
366         free(session->remote_id);
367         osrfLogDebug( OSRF_LOG_MARK,  "App Session [%s] [%s] resetting remote id to %s",
368                         session->remote_service, session->session_id, session->orig_remote_id );
369
370         session->remote_id = strdup(session->orig_remote_id);
371 }
372
373 void osrf_app_session_set_remote( osrf_app_session* session, char* remote_id ) {
374         if(session == NULL)
375                 return;
376         if( session->remote_id )
377                 free(session->remote_id );
378         session->remote_id = strdup( remote_id );
379 }
380
381 /** pushes the given message into the result list of the app_request
382   with the given request_id */
383 int osrf_app_session_push_queue( 
384                 osrf_app_session* session, osrf_message* msg ){
385         if(session == NULL || msg == NULL) return 0;
386
387         osrf_app_request* req = OSRF_LIST_GET_INDEX( session->request_queue, msg->thread_trace );
388         if(req == NULL) return 0;
389         _osrf_app_request_push_queue( req, msg );
390
391         return 0;
392 }
393
394 int osrfAppSessionConnect( osrf_app_session* session ) { 
395         return osrf_app_session_connect(session);
396 }
397
398
399 /** Attempts to connect to the remote service */
400 int osrf_app_session_connect(osrf_app_session* session){
401         
402         if(session == NULL)
403                 return 0;
404
405         if(session->state == OSRF_SESSION_CONNECTED) {
406                 return 1;
407         }
408
409         int timeout = 5; /* XXX CONFIG VALUE */
410
411         osrfLogDebug( OSRF_LOG_MARK,  "AppSession connecting to %s", session->remote_id );
412
413         /* defaulting to protocol 1 for now */
414         osrf_message* con_msg = osrf_message_init( CONNECT, session->thread_trace, 1 );
415         osrf_app_session_reset_remote( session );
416         session->state = OSRF_SESSION_CONNECTING;
417         int ret = _osrf_app_session_send( session, con_msg );
418         osrf_message_free(con_msg);
419         if(ret) return 0;
420
421         time_t start = time(NULL);      
422         time_t remaining = (time_t) timeout;
423
424         while( session->state != OSRF_SESSION_CONNECTED && remaining >= 0 ) {
425                 osrf_app_session_queue_wait( session, remaining, NULL );
426                 remaining -= (int) (time(NULL) - start);
427         }
428
429         if(session->state == OSRF_SESSION_CONNECTED)
430                 osrfLogDebug( OSRF_LOG_MARK, " * Connected Successfully to %s", session->remote_service );
431
432         if(session->state != OSRF_SESSION_CONNECTED)
433                 return 0;
434
435         return 1;
436 }
437
438
439
440 /** Disconnects from the remote service */
441 int osrf_app_session_disconnect( osrf_app_session* session){
442         if(session == NULL)
443                 return 1;
444
445         if(session->state == OSRF_SESSION_DISCONNECTED)
446                 return 1;
447
448         if(session->stateless && session->state != OSRF_SESSION_CONNECTED) {
449                 osrfLogDebug( OSRF_LOG_MARK,  
450                                 "Exiting disconnect on stateless session %s", 
451                                 session->session_id);
452                 return 1;
453         }
454
455         osrfLogDebug(OSRF_LOG_MARK,  "AppSession disconnecting from %s", session->remote_id );
456
457         osrf_message* dis_msg = osrf_message_init( DISCONNECT, session->thread_trace, 1 );
458         _osrf_app_session_send( session, dis_msg );
459         session->state = OSRF_SESSION_DISCONNECTED;
460
461         osrf_message_free( dis_msg );
462         osrf_app_session_reset_remote( session );
463         return 1;
464 }
465
466 int osrf_app_session_request_resend( osrf_app_session* session, int req_id ) {
467         osrf_app_request* req = OSRF_LIST_GET_INDEX( session->request_queue, req_id );
468         return _osrf_app_request_resend( req );
469 }
470
471
472 int osrfAppSessionSendBatch( osrfAppSession* session, osrf_message* msgs[], int size ) {
473
474         if( !(session && msgs && size > 0) ) return 0;
475         int retval = 0;
476
477         osrfMessage* msg = msgs[0];
478
479         if(msg) {
480
481                 osrf_app_session_queue_wait( session, 0, NULL );
482
483                 if(session->state != OSRF_SESSION_CONNECTED)  {
484
485                         if(session->stateless) { /* stateless session always send to the root listener */
486                                 osrf_app_session_reset_remote(session);
487
488                         } else { 
489
490                                 /* do an auto-connect if necessary */
491                                 if( ! session->stateless &&
492                                         (msg->m_type != CONNECT) && 
493                                         (msg->m_type != DISCONNECT) &&
494                                         (session->state != OSRF_SESSION_CONNECTED) ) {
495
496                                         if(!osrf_app_session_connect( session )) 
497                                                 return 0;
498                                 }
499                         }
500                 }
501         }
502
503         char* string = osrfMessageSerializeBatch(msgs, size);
504
505         if( string ) {
506
507                 transport_message* t_msg = message_init( 
508                                 string, "", session->session_id, session->remote_id, NULL );
509       message_set_osrf_xid( t_msg, osrfLogGetXid() );
510
511                 retval = client_send_message( session->transport_handle, t_msg );
512
513                 if( retval ) osrfLogError(OSRF_LOG_MARK, "client_send_message failed");
514
515                 osrfLogInfo(OSRF_LOG_MARK, "[%s] sent %d bytes of data to %s",
516                         session->remote_service, strlen(string), t_msg->recipient );
517
518                 osrfLogDebug(OSRF_LOG_MARK, "Sent: %s", string );
519
520                 free(string);
521                 message_free( t_msg );
522         }
523
524         return retval; 
525 }
526
527
528
529 int _osrf_app_session_send( osrf_app_session* session, osrf_message* msg ){
530         if( !(session && msg) ) return 0;
531         osrfMessage* a[1];
532         a[0] = msg;
533         return osrfAppSessionSendBatch( session, a, 1 );
534 }
535
536
537
538
539 /**  Waits up to 'timeout' seconds for some data to arrive.
540   * Any data that arrives will be processed according to its
541   * payload and message type.  This method will return after
542   * any data has arrived.
543   */
544 int osrf_app_session_queue_wait( osrf_app_session* session, int timeout, int* recvd ){
545         if(session == NULL) return 0;
546         int ret_val = 0;
547         osrfLogDebug(OSRF_LOG_MARK,  "AppSession in queue_wait with timeout %d", timeout );
548         ret_val = osrf_stack_entry_point(session->transport_handle, timeout, recvd);
549         return ret_val;
550 }
551
552 /** Disconnects (if client) and removes the given session from the global session cache 
553   * ! This free's all attached app_requests ! 
554   */
555 void osrfAppSessionFree( osrfAppSession* ses ) {
556         osrf_app_session_destroy( ses );
557 }
558
559
560 void osrf_app_session_destroy( osrf_app_session* session ){
561         if(session == NULL) return;
562
563         osrfLogDebug(OSRF_LOG_MARK,  "AppSession [%s] [%s] destroying self and deleting requests", 
564                         session->remote_service, session->session_id );
565         if(session->type == OSRF_SESSION_CLIENT 
566                         && session->state != OSRF_SESSION_DISCONNECTED ) { /* disconnect if we're a client */
567                 osrf_message* dis_msg = osrf_message_init( DISCONNECT, session->thread_trace, 1 );
568                 _osrf_app_session_send( session, dis_msg ); 
569                 osrf_message_free(dis_msg);
570         }
571
572         osrfHashRemove( osrfAppSessionCache, session->session_id );
573         _osrf_app_session_free( session );
574 }
575
576 osrf_message* osrfAppSessionRequestRecv(
577                 osrf_app_session* session, int req_id, int timeout ) {
578         return osrf_app_session_request_recv( session, req_id, timeout );
579 }
580 osrf_message* osrf_app_session_request_recv( 
581                 osrf_app_session* session, int req_id, int timeout ) {
582         if(req_id < 0 || session == NULL)
583                 return NULL;
584         osrf_app_request* req = OSRF_LIST_GET_INDEX( session->request_queue, req_id );
585         return _osrf_app_request_recv( req, timeout );
586 }
587
588
589
590 int osrfAppRequestRespond( osrfAppSession* ses, int requestId, jsonObject* data ) {
591         if(!ses || ! data ) return -1;
592
593         osrf_message* msg = osrf_message_init( RESULT, requestId, 1 );
594         char* json = jsonObjectToJSON( data );
595
596         osrf_message_set_result_content( msg, json );
597         _osrf_app_session_send( ses, msg ); 
598
599         free(json);
600         osrf_message_free( msg );
601
602         return 0;
603 }
604
605
606 int osrfAppRequestRespondComplete( 
607                 osrfAppSession* ses, int requestId, jsonObject* data ) {
608
609         osrf_message* payload = osrf_message_init( RESULT, requestId, 1 );
610         osrf_message_set_status_info( payload, NULL, "OK", OSRF_STATUS_OK );
611
612         osrf_message* status = osrf_message_init( STATUS, requestId, 1);
613         osrf_message_set_status_info( status, "osrfConnectStatus", "Request Complete", OSRF_STATUS_COMPLETE );
614         
615         if (data) {
616                 char* json = jsonObjectToJSON( data );
617                 osrf_message_set_result_content( payload, json );
618                 free(json);
619
620                 osrfMessage* ms[2];
621                 ms[0] = payload;
622                 ms[1] = status;
623
624                 osrfAppSessionSendBatch( ses, ms, 2 );
625
626                 osrf_message_free( payload );
627         } else {
628                 osrfAppSessionSendBatch( ses, &status, 1 );
629         }
630
631         osrf_message_free( status );
632
633         return 0;
634 }
635
636 int osrfAppSessionStatus( osrfAppSession* ses, int type, char* name, int reqId, char* message ) {
637
638         if(ses) {
639                 osrf_message* msg = osrf_message_init( STATUS, reqId, 1);
640                 osrf_message_set_status_info( msg, name, message, type );
641                 _osrf_app_session_send( ses, msg ); 
642                 osrf_message_free( msg );
643                 return 0;
644         }
645         return -1;
646 }
647
648
649
650
651
652