]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/gateway/osrf_websocket_translator.c
LP#1268619: websocket; docs, more memory mgmt
[OpenSRF.git] / src / gateway / osrf_websocket_translator.c
1 /* -----------------------------------------------------------------------
2  * Copyright 2012 Equinox Software, Inc.
3  * Bill Erickson <berick@esilibrary.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
17 /**
18  * websocket <-> opensrf gateway.  Wrapped opensrf messages are extracted
19  * and relayed to the opensrf network.  Responses are pulled from the opensrf
20  * network and passed back to the client.  Messages are analyzed to determine
21  * when a connect/disconnect occurs, so that the cache of recipients can be
22  * properly managed.  We also activity-log REQUEST messages.
23  *
24  * Messages to/from the websocket client take the following form:
25  * {
26  *   "service"  : "opensrf.foo", // required
27  *   "thread"   : "123454321",   // AKA thread. required for follow-up requests; max 64 chars.
28  *   "log_xid"  : "123..32",     // optional log trace ID, max 64 chars;
29  *   "osrf_msg" : {<osrf_msg>}   // required
30  * }
31  *
32  * Each translator operates with two threads.  One thread receives messages
33  * from the websocket client, translates, and relays them to the opensrf 
34  * network. The second thread collects responses from the opensrf network and 
35  * relays them back to the websocket client.
36  *
37  * After the initial setup, all thread actions occur within a thread mutex.
38  * The desired affect is a non-threaded application that uses threads for 
39  * the sole purpose of having one thread listening for incoming data, while
40  * a second thread listens for responses.  When either thread awakens, it's
41  * the only thread in town until it goes back to sleep (i.e. listening on 
42  * its socket for data).
43  *
44  * Note that with a "thread", which allows us to identify the opensrf session,
45  * the caller does not need to provide a recipient address.  The "service" is
46  * only required to start a new opensrf session.  After the sesession is 
47  * started, all future communication is based solely on the thread.  However,
48  * the "service" should be passed by the caller for all requests to ensure it
49  * is properly logged in the activity log.
50  */
51
52 /**
53  * TODO:
54  * short-timeout mode for brick detachment where inactivity timeout drops way 
55  * down for graceful disconnects.
56  */
57
58 #include "httpd.h"
59 #include "apr_strings.h"
60 #include "apr_thread_proc.h"
61 #include "apr_hash.h"
62 #include "websocket_plugin.h"
63 #include "opensrf/log.h"
64 #include "opensrf/osrf_json.h"
65 #include "opensrf/transport_client.h"
66 #include "opensrf/transport_message.h"
67 #include "opensrf/osrf_system.h"                                                
68 #include "opensrf/osrfConfig.h"
69
70 #define MAX_THREAD_SIZE 64
71 #define RECIP_BUF_SIZE 128
72 #define WEBSOCKET_TRANSLATOR_INGRESS "ws-translator-v1"
73
74 typedef struct _osrfWebsocketTranslator {
75
76     /** Our handle for communicating with the caller */
77     const WebSocketServer *server;
78     
79     /**
80      * Standalone, per-process APR pool.  Primarily
81      * there for managing thread data, which lasts 
82      * the duration of the process.
83      */
84     apr_pool_t *main_pool;
85
86     /**
87      * Map of thread => drone-xmpp-address.  Maintaining this
88      * map internally means the caller never need know about
89      * internal XMPP addresses and the server doesn't have to 
90      * verify caller-specified recipient addresses.  It's
91      * all managed internally.
92      */
93     apr_hash_t *session_cache; 
94
95     /**
96      * session_pool contains the key/value pairs stored in
97      * the session_cache.  The pool is regularly destroyed
98      * and re-created to avoid long-term memory consumption
99      */
100     apr_pool_t *session_pool;
101
102     /**
103      * Thread responsible for collecting responses on the opensrf
104      * network and relaying them back to the caller
105      */
106     apr_thread_t *responder_thread;
107
108     /**
109      * All message handling code is wrapped in a thread mutex such
110      * that all actions (after the initial setup) are serialized
111      * to minimize the possibility of multi-threading snafus.
112      */
113     apr_thread_mutex_t *mutex;
114
115     /**
116      * True if a websocket client is currently connected
117      */
118     int client_connected;
119
120     /** OpenSRF jouter name */
121     char* osrf_router;
122
123     /** OpenSRF domain */
124     char* osrf_domain;
125
126 } osrfWebsocketTranslator;
127
128 static osrfWebsocketTranslator *trans = NULL;
129 static transport_client *osrf_handle = NULL;
130 static char recipient_buf[RECIP_BUF_SIZE]; // reusable recipient buffer
131
132 static void clear_cached_recipient(const char* thread) {
133     apr_pool_t *pool = NULL;                                                
134
135     if (apr_hash_get(trans->session_cache, thread, APR_HASH_KEY_STRING)) {
136
137         osrfLogDebug(OSRF_LOG_MARK, "WS removing cached recipient on disconnect");
138
139         // remove it from the hash
140         apr_hash_set(trans->session_cache, thread, APR_HASH_KEY_STRING, NULL);
141
142         if (apr_hash_count(trans->session_cache) == 0) {
143             osrfLogDebug(OSRF_LOG_MARK, "WS re-setting session_pool");
144
145             // memory accumulates in the session_pool as sessions are cached then 
146             // un-cached.  Un-caching removes strings from the hash, but not the 
147             // pool itself.  That only happens when the pool is destroyed. Here
148             // we destroy the session pool to clear any lingering memory, then
149             // re-create it for future caching.
150             apr_pool_destroy(trans->session_pool);
151     
152             if (apr_pool_create(&pool, NULL) != APR_SUCCESS) {
153                 osrfLogError(OSRF_LOG_MARK, "WS Unable to create session_pool");
154                 trans->session_pool = NULL;
155                 return;
156             }
157
158             trans->session_pool = pool;
159         }
160     }
161 }
162
163
164 void* osrf_responder_thread_main_body(transport_message *tmsg) {
165
166     osrfList *msg_list = NULL;
167     osrfMessage *one_msg = NULL;
168     int i;
169
170     osrfLogDebug(OSRF_LOG_MARK, 
171         "WS received opensrf response for thread=%s, xid=%s", 
172             tmsg->thread, tmsg->osrf_xid);
173
174     // first we need to perform some maintenance
175     msg_list = osrfMessageDeserialize(tmsg->body, NULL);
176
177     for (i = 0; i < msg_list->size; i++) {
178         one_msg = OSRF_LIST_GET_INDEX(msg_list, i);
179
180         osrfLogDebug(OSRF_LOG_MARK, 
181             "WS returned response of type %d", one_msg->m_type);
182
183         /*  if our client just successfully connected to an opensrf service,
184             cache the sender so that future calls on this thread will use
185             the correct recipient. */
186         if (one_msg && one_msg->m_type == STATUS) {
187
188
189             // only cache recipients if the client is still connected
190             if (trans->client_connected && 
191                     one_msg->status_code == OSRF_STATUS_OK) {
192
193                 if (!apr_hash_get(trans->session_cache, 
194                         tmsg->thread, APR_HASH_KEY_STRING)) {
195
196                     osrfLogDebug(OSRF_LOG_MARK, 
197                         "WS caching sender thread=%s, sender=%s", 
198                         tmsg->thread, tmsg->sender);
199
200                     apr_hash_set(trans->session_cache, 
201                         apr_pstrdup(trans->session_pool, tmsg->thread),
202                         APR_HASH_KEY_STRING, 
203                         apr_pstrdup(trans->session_pool, tmsg->sender));
204                 }
205
206             } else {
207
208                 // connection timed out; clear the cached recipient
209                 // regardless of whether the client is still connected
210                 if (one_msg->status_code == OSRF_STATUS_TIMEOUT)
211                     clear_cached_recipient(tmsg->thread);
212             }
213         }
214     }
215
216     // maintenance is done
217     osrfListFree(msg_list);
218
219     if (!trans->client_connected) {
220
221         osrfLogDebug(OSRF_LOG_MARK, 
222             "WS discarding response for thread=%s, xid=%s", 
223             tmsg->thread, tmsg->osrf_xid);
224
225         return;
226     }
227
228     
229     // client is still connected. 
230     // relay the response messages to the client
231     jsonObject *msg_wrapper = NULL;
232     char *msg_string = NULL;
233
234     // build the wrapper object
235     msg_wrapper = jsonNewObject(NULL);
236     jsonObjectSetKey(msg_wrapper, "thread", jsonNewObject(tmsg->thread));
237     jsonObjectSetKey(msg_wrapper, "log_xid", jsonNewObject(tmsg->osrf_xid));
238     jsonObjectSetKey(msg_wrapper, "osrf_msg", jsonParseRaw(tmsg->body));
239
240     if (tmsg->is_error) {
241         osrfLogError(OSRF_LOG_MARK, 
242             "WS received jabber error message in response to thread=%s and xid=%s", 
243             tmsg->thread, tmsg->osrf_xid);
244         jsonObjectSetKey(msg_wrapper, "transport_error", jsonNewBoolObject(1));
245     }
246
247     msg_string = jsonObjectToJSONRaw(msg_wrapper);
248
249     // drop the JSON on the outbound wire
250     trans->server->send(trans->server, MESSAGE_TYPE_TEXT, 
251         (unsigned char*) msg_string, strlen(msg_string));
252
253     free(msg_string);
254     jsonObjectFree(msg_wrapper);
255
256 }
257
258 /**
259  * Responder thread main body.
260  * Collects responses from the opensrf network and relays them to the 
261  * websocket caller.
262  */
263 void* APR_THREAD_FUNC osrf_responder_thread_main(apr_thread_t *thread, void *data) {
264
265     transport_message *tmsg;
266     while (1) {
267
268         if (apr_thread_mutex_unlock(trans->mutex) != APR_SUCCESS) {
269             osrfLogError(OSRF_LOG_MARK, "WS error un-locking thread mutex");
270             return NULL;
271         }
272
273         // wait for a response
274         tmsg = client_recv(osrf_handle, -1);
275
276         if (!tmsg) continue; // early exit on interrupt
277
278         if (apr_thread_mutex_lock(trans->mutex) != APR_SUCCESS) {
279             osrfLogError(OSRF_LOG_MARK, "WS error locking thread mutex");
280             return NULL;
281         }
282
283         osrf_responder_thread_main_body(tmsg);
284         message_free(tmsg);                                                         
285     }
286
287     return NULL;
288 }
289
290
291
292 /**
293  * Connect to OpenSRF, create the main pool, responder thread
294  * session cache and session pool.
295  */
296 int child_init(const WebSocketServer *server) {
297
298     apr_pool_t *pool = NULL;                                                
299     apr_thread_t *thread = NULL;
300     apr_threadattr_t *thread_attr = NULL;
301     apr_thread_mutex_t *mutex = NULL;
302     request_rec *r = server->request(server);
303         
304     osrfLogDebug(OSRF_LOG_MARK, "WS child_init");
305
306     // osrf_handle will already be connected if this is not the first request
307     // served by this process.
308     if ( !(osrf_handle = osrfSystemGetTransportClient()) ) {
309         char* config_file = "/openils/conf/opensrf_core.xml";
310         char* config_ctx = "gateway"; //TODO config
311         if (!osrfSystemBootstrapClientResc(config_file, config_ctx, "websocket")) {   
312             osrfLogError(OSRF_LOG_MARK, 
313                 "WS unable to bootstrap OpenSRF client with config %s", config_file); 
314             return 1;
315         }
316
317         osrf_handle = osrfSystemGetTransportClient();
318     }
319
320     // create a standalone pool for our translator data
321     if (apr_pool_create(&pool, NULL) != APR_SUCCESS) {
322         osrfLogError(OSRF_LOG_MARK, "WS Unable to create apr_pool");
323         return 1;
324     }
325
326
327     // allocate our static translator instance
328     trans = (osrfWebsocketTranslator*) 
329         apr_palloc(pool, sizeof(osrfWebsocketTranslator));
330
331     if (trans == NULL) {
332         osrfLogError(OSRF_LOG_MARK, "WS Unable to create translator");
333         return 1;
334     }
335
336     trans->main_pool = pool;
337     trans->server = server;
338     trans->osrf_router = osrfConfigGetValue(NULL, "/router_name");                      
339     trans->osrf_domain = osrfConfigGetValue(NULL, "/domain");
340
341     trans->session_cache = apr_hash_make(pool);
342
343     if (trans->session_cache == NULL) {
344         osrfLogError(OSRF_LOG_MARK, "WS unable to create session cache");
345         return 1;
346     }
347
348     // Create the responder thread.  Once created, 
349     // it runs for the lifetime of this process.
350     if ( (apr_threadattr_create(&thread_attr, trans->main_pool) == APR_SUCCESS) &&
351          (apr_threadattr_detach_set(thread_attr, 0) == APR_SUCCESS) &&
352          (apr_thread_create(&thread, thread_attr, 
353                 osrf_responder_thread_main, trans, trans->main_pool) == APR_SUCCESS)) {
354
355         trans->responder_thread = thread;
356         
357     } else {
358         osrfLogError(OSRF_LOG_MARK, "WS unable to create responder thread");
359         return 1;
360     }
361
362     if (apr_thread_mutex_create(
363             &mutex, APR_THREAD_MUTEX_UNNESTED, 
364             trans->main_pool) != APR_SUCCESS) {
365         osrfLogError(OSRF_LOG_MARK, "WS unable to create thread mutex");
366         return 1;
367     }
368
369     trans->mutex = mutex;
370
371     return APR_SUCCESS;
372 }
373
374 /**
375  * Create the per-client translator
376  */
377 void* CALLBACK on_connect_handler(const WebSocketServer *server) {
378     request_rec *r = server->request(server);
379     apr_pool_t *pool;
380
381     osrfLogDebug(OSRF_LOG_MARK, 
382         "WS connect from %s", r->connection->remote_ip); 
383         //"WS connect from %s", r->connection->client_ip); // apache 2.4
384
385     if (!trans) {
386         // first connection
387         if (child_init(server) != APR_SUCCESS) {
388             return NULL;
389         }
390     }
391
392     // create a standalone pool for the session cache values
393     // this pool will be destroyed and re-created regularly
394     // to clear session memory
395     if (apr_pool_create(&pool, r->pool) != APR_SUCCESS) {
396         osrfLogError(OSRF_LOG_MARK, "WS Unable to create apr_pool");
397         return NULL;
398     }
399
400     trans->session_pool = pool;
401     trans->client_connected = 1;
402     return trans;
403 }
404
405
406 /** 
407  * for each inbound opensrf message:
408  * 1. Stamp the ingress
409  * 2. REQUEST: log it as activity
410  * 3. DISCONNECT: remove the cached recipient
411  * then re-string-ify for xmpp delivery
412  */
413
414 static char* extract_inbound_messages(
415         const request_rec *r, 
416         const char* service, 
417         const char* thread, 
418         const char* recipient, 
419         const jsonObject *osrf_msg) {
420
421     int i;
422     int num_msgs = osrf_msg->size;
423     osrfMessage* msg;
424     osrfMessage* msg_list[num_msgs];
425
426     // here we do an extra json round-trip to get the data
427     // in a form osrf_message_deserialize can understand
428     char *osrf_msg_json = jsonObjectToJSON(osrf_msg);
429     osrf_message_deserialize(osrf_msg_json, msg_list, num_msgs);
430     free(osrf_msg_json);
431
432     // should we require the caller to always pass the service?
433     if (service == NULL) service = "";
434
435     for(i = 0; i < num_msgs; i++) {
436         msg = msg_list[i];
437         osrfMessageSetIngress(msg, WEBSOCKET_TRANSLATOR_INGRESS);
438
439         switch(msg->m_type) {
440
441             case REQUEST: {
442                 const jsonObject* params = msg->_params;
443                 growing_buffer* act = buffer_init(128);
444                 char* method = msg->method_name;
445                 buffer_fadd(act, "[%s] [%s] %s %s", 
446                     r->connection->remote_ip, "", service, method);
447
448                 const jsonObject* obj = NULL;
449                 int i = 0;
450                 const char* str;
451                 int redactParams = 0;
452                 while( (str = osrfStringArrayGetString(log_protect_arr, i++)) ) {
453                     if(!strncmp(method, str, strlen(str))) {
454                         redactParams = 1;
455                         break;
456                     }
457                 }
458                 if(redactParams) {
459                     OSRF_BUFFER_ADD(act, " **PARAMS REDACTED**");
460                 } else {
461                     i = 0;
462                     while((obj = jsonObjectGetIndex(params, i++))) {
463                         char* str = jsonObjectToJSON(obj);
464                         if( i == 1 )
465                             OSRF_BUFFER_ADD(act, " ");
466                         else
467                             OSRF_BUFFER_ADD(act, ", ");
468                         OSRF_BUFFER_ADD(act, str);
469                         free(str);
470                     }
471                 }
472                 osrfLogActivity(OSRF_LOG_MARK, "%s", act->buf);
473                 buffer_free(act);
474                 break;
475             }
476
477             case DISCONNECT:
478                 clear_cached_recipient(thread);
479                 break;
480         }
481     }
482
483     return osrfMessageSerializeBatch(msg_list, num_msgs);
484 }
485
486 /**
487  * Parse opensrf request and relay the request to the opensrf network.
488  */
489 static size_t on_message_handler_body(void *data,
490                 const WebSocketServer *server, const int type, 
491                 unsigned char *buffer, const size_t buffer_size) {
492
493     request_rec *r = server->request(server);
494
495     jsonObject *msg_wrapper = NULL; // free me
496     const jsonObject *tmp_obj = NULL;
497     const jsonObject *osrf_msg = NULL;
498     const char *service = NULL;
499     const char *thread = NULL;
500     const char *log_xid = NULL;
501     char *msg_body = NULL;
502     char *recipient = NULL;
503     int i;
504
505     if (buffer_size <= 0) return OK;
506
507     osrfLogDebug(OSRF_LOG_MARK, "WS received message size=%d", buffer_size);
508
509     // buffer may not be \0-terminated, which jsonParse requires
510     char buf[buffer_size + 1];
511     memcpy(buf, buffer, buffer_size);
512     buf[buffer_size] = '\0';
513
514     msg_wrapper = jsonParse(buf);
515
516     if (msg_wrapper == NULL) {
517         osrfLogWarning(OSRF_LOG_MARK, "WS Invalid JSON: %s", buf);
518         return HTTP_BAD_REQUEST;
519     }
520
521     osrf_msg = jsonObjectGetKeyConst(msg_wrapper, "osrf_msg");
522
523     if (tmp_obj = jsonObjectGetKeyConst(msg_wrapper, "service")) 
524         service = jsonObjectGetString(tmp_obj);
525
526     if (tmp_obj = jsonObjectGetKeyConst(msg_wrapper, "thread")) 
527         thread = jsonObjectGetString(tmp_obj);
528
529     if (tmp_obj = jsonObjectGetKeyConst(msg_wrapper, "log_xid")) 
530         log_xid = jsonObjectGetString(tmp_obj);
531
532     if (log_xid) {
533
534         // use the caller-provide log trace id
535         if (strlen(log_xid) > MAX_THREAD_SIZE) {
536             osrfLogWarning(OSRF_LOG_MARK, "WS log_xid exceeds max length");
537             return HTTP_BAD_REQUEST;
538         }
539
540         // TODO: make this work with non-client and make this call accept 
541         // const char*'s.  casting to (char*) for now to silence warnings.
542         osrfLogSetXid((char*) log_xid); 
543
544     } else {
545         // generate a new log trace id for this relay
546         osrfLogMkXid();
547     }
548
549     if (thread) {
550
551         if (strlen(thread) > MAX_THREAD_SIZE) {
552             osrfLogWarning(OSRF_LOG_MARK, "WS thread exceeds max length");
553             return HTTP_BAD_REQUEST;
554         }
555
556         // since clients can provide their own threads at session start time,
557         // the presence of a thread does not guarantee a cached recipient
558         recipient = (char*) apr_hash_get(
559             trans->session_cache, thread, APR_HASH_KEY_STRING);
560
561         if (recipient) {
562             osrfLogDebug(OSRF_LOG_MARK, "WS found cached recipient %s", recipient);
563         }
564     }
565
566     if (!recipient) {
567
568         if (service) {
569             int size = snprintf(recipient_buf, RECIP_BUF_SIZE - 1,
570                 "%s@%s/%s", trans->osrf_router, trans->osrf_domain, service);                                    
571             recipient_buf[size] = '\0';                                          
572             recipient = recipient_buf;
573
574         } else {
575             osrfLogWarning(OSRF_LOG_MARK, "WS Unable to determine recipient");
576             return HTTP_BAD_REQUEST;
577         }
578     }
579
580     osrfLogDebug(OSRF_LOG_MARK, 
581         "WS relaying message thread=%s, xid=%s, recipient=%s", 
582             thread, osrfLogGetXid(), recipient);
583
584     msg_body = extract_inbound_messages(
585         r, service, thread, recipient, osrf_msg);
586
587     transport_message *tmsg = message_init(
588         msg_body, NULL, thread, recipient, NULL);
589
590     message_set_osrf_xid(tmsg, osrfLogGetXid());
591     client_send_message(osrf_handle, tmsg);
592
593
594     osrfLogClearXid();
595     message_free(tmsg);                                                         
596     jsonObjectFree(msg_wrapper);
597     free(msg_body);
598
599     return OK;
600 }
601
602 static size_t CALLBACK on_message_handler(void *data,
603                 const WebSocketServer *server, const int type, 
604                 unsigned char *buffer, const size_t buffer_size) {
605
606     if (apr_thread_mutex_lock(trans->mutex) != APR_SUCCESS) {
607         osrfLogError(OSRF_LOG_MARK, "WS error locking thread mutex");
608         return 1; // TODO: map to apr_status_t value?
609     }
610
611     apr_status_t stat = on_message_handler_body(data, server, type, buffer, buffer_size);
612
613     if (apr_thread_mutex_unlock(trans->mutex) != APR_SUCCESS) {
614         osrfLogError(OSRF_LOG_MARK, "WS error locking thread mutex");
615         return 1;
616     }
617
618     return stat;
619 }
620
621
622 /**
623  * Clear the session cache, release the session pool
624  */
625 void CALLBACK on_disconnect_handler(
626     void *data, const WebSocketServer *server) {
627
628     osrfWebsocketTranslator *trans = (osrfWebsocketTranslator*) data;
629     trans->client_connected = 0;
630     
631     // ensure no errant session data is sticking around
632     apr_hash_clear(trans->session_cache);
633
634     // strictly speaking, this pool will get destroyed when
635     // r->pool is destroyed, but it doesn't hurt to explicitly
636     // destroy it ourselves.
637     apr_pool_destroy(trans->session_pool);
638     trans->session_pool = NULL;
639
640     request_rec *r = server->request(server);
641
642     osrfLogDebug(OSRF_LOG_MARK, 
643         "WS disconnect from %s", r->connection->remote_ip); 
644         //"WS disconnect from %s", r->connection->client_ip); // apache 2.4
645 }
646
647 /**
648  * Be nice and clean up our mess
649  */
650 void CALLBACK on_destroy_handler(WebSocketPlugin *plugin) {
651     if (trans) {
652         apr_thread_exit(trans->responder_thread, APR_SUCCESS);
653         apr_thread_mutex_destroy(trans->mutex);
654         apr_pool_destroy(trans->session_pool);
655         apr_pool_destroy(trans->main_pool);
656     }
657
658     trans = NULL;
659 }
660
661 static WebSocketPlugin osrf_websocket_plugin = {
662     sizeof(WebSocketPlugin),
663     WEBSOCKET_PLUGIN_VERSION_0,
664     on_destroy_handler,
665     on_connect_handler,
666     on_message_handler,
667     on_disconnect_handler
668 };
669
670 extern EXPORT WebSocketPlugin * CALLBACK osrf_websocket_init() {
671     return &osrf_websocket_plugin;
672 }
673