]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/gateway/osrf_json_gateway.c
added request duration
[OpenSRF.git] / src / gateway / osrf_json_gateway.c
1 #include "apachetools.h"
2 #include "opensrf/osrf_app_session.h"
3 #include "opensrf/osrf_system.h"
4 #include "opensrf/osrfConfig.h"
5 #include "objson/object.h"
6 #include "objson/json2xml.h"
7 #include <sys/time.h>
8 #include <sys/resource.h>
9
10
11 #define MODULE_NAME "osrf_json_gateway_module"
12 #define GATEWAY_CONFIG "OSRFGatewayConfig"
13 #define CONFIG_CONTEXT "gateway"
14
15 #define GATEWAY_DEFAULT_CONFIG "/openils/conf/opensrf_core.xml"
16
17
18 /* our config structure */
19 typedef struct { 
20         char* configfile;  /* our bootstrap config file */
21 } osrf_json_gateway_config;
22
23 module AP_MODULE_DECLARE_DATA osrf_json_gateway_module;
24
25 char* osrf_json_gateway_config_file = NULL;
26 int bootstrapped = 0;
27 int numserved = 0;
28 osrfStringArray* allowedServices = NULL;
29
30 static const char* osrf_json_gateway_set_config(cmd_parms *parms, void *config, const char *arg) {
31         osrf_json_gateway_config  *cfg;
32         cfg = ap_get_module_config(parms->server->module_config, &osrf_json_gateway_module);
33         cfg->configfile = (char*) arg;
34         osrf_json_gateway_config_file = (char*) arg;
35         return NULL;
36 }
37
38 /* tell apache about our commands */
39 static const command_rec osrf_json_gateway_cmds[] = {
40         AP_INIT_TAKE1( GATEWAY_CONFIG, osrf_json_gateway_set_config, 
41                         NULL, RSRC_CONF, "osrf json gateway config file"),
42         {NULL}
43 };
44
45 /* build the config object */
46 static void* osrf_json_gateway_create_config( apr_pool_t* p, server_rec* s) {
47         osrf_json_gateway_config* cfg = (osrf_json_gateway_config*) 
48                         apr_palloc(p, sizeof(osrf_json_gateway_config));
49         cfg->configfile = GATEWAY_DEFAULT_CONFIG;
50         return (void*) cfg;
51 }
52
53
54 static void osrf_json_gateway_child_init(apr_pool_t *p, server_rec *s) {
55
56         char* cfg = osrf_json_gateway_config_file;
57         if( ! osrf_system_bootstrap_client( cfg, CONFIG_CONTEXT ) ) {
58                 ap_log_error( APLOG_MARK, APLOG_ERR, 0, s, 
59                         "Unable to Bootstrap OpenSRF Client with config %s..", cfg);
60                 return;
61         }
62
63         bootstrapped = 1;
64         allowedServices = osrfNewStringArray(8);
65         osrfLogInfo(OSRF_LOG_MARK, "Bootstrapping gateway child for requests");
66         osrfConfigGetValueList( NULL, allowedServices, "/services/service" );
67
68         int i;
69         for( i = 0; i < allowedServices->size; i++ ) {
70                 fprintf(stderr, "allowed service: %s\n", 
71                         osrfStringArrayGetString(allowedServices, i));
72         }
73
74
75 #ifdef OSRF_GATEWAY_ENABLE_RLIMIT /* emergency test measures only */
76         struct rlimit lim = { 536870912, 536870912 }; /* 512MB */
77         setrlimit(RLIMIT_AS, &lim);
78         setrlimit(RLIMIT_MEMLOCK,&lim);
79         setrlimit(RLIMIT_STACK, &lim);
80         setrlimit(RLIMIT_DATA,&lim);
81
82         struct rlimit lim2;
83         getrlimit(RLIMIT_DATA, &lim2);
84         osrfLogDebug(OSRF_LOG_MARK, "rlimit for data set to %d", lim2.rlim_cur);
85 #endif
86
87 }
88
89 static int osrf_json_gateway_method_handler (request_rec *r) {
90
91         /* make sure we're needed first thing*/
92         if (strcmp(r->handler, MODULE_NAME )) return DECLINED;
93
94         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: entered request handler");
95
96         /* verify we are connected */
97         if( !bootstrapped || !osrf_system_get_transport_client()) {
98                 ap_log_rerror( APLOG_MARK, APLOG_ERR, 0, r, "Cannot process request "
99                                 "because the OpenSRF JSON gateway has not been bootstrapped...");
100                 return HTTP_INTERNAL_SERVER_ERROR;
101         }
102
103         osrfLogSetAppname("osrf_json_gw");
104
105         char* service           = NULL; /* service to connect to */
106         char* method            = NULL; /* method to perform */
107         char* format            = NULL; /* method to perform */
108         char* a_l                       = NULL; /* request api level */
109         int   isXML                     = 0;
110         int   api_level = 1;
111         apr_table_t* cookies = NULL;
112
113         r->allowed |= (AP_METHOD_BIT << M_GET);
114         r->allowed |= (AP_METHOD_BIT << M_POST);
115
116         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: parsing URL params");
117         string_array* mparams   = NULL;
118         string_array* params            = apacheParseParms(r); /* free me */
119         service         = apacheGetFirstParamValue( params, "service" );
120         method          = apacheGetFirstParamValue( params, "method" ); 
121         format          = apacheGetFirstParamValue( params, "format" ); 
122         a_l                     = apacheGetFirstParamValue( params, "api_level" ); 
123         mparams         = apacheGetParamValues( params, "param" ); /* free me */
124
125         if (a_l)
126                 api_level = atoi(a_l);
127
128         if (format && !strcasecmp(format, "xml" )) {
129                 isXML = 1;
130                 ap_set_content_type(r, "application/xml");
131         } else {
132                 ap_set_content_type(r, "text/plain");
133         }
134
135         int ret = OK;
136
137         if(!(service && method) || 
138                 !osrfStringArrayContains(allowedServices, service)) {
139
140                 osrfLogError(OSRF_LOG_MARK, 
141                         "Service [%s] not found or not allowed", service);
142                 ret = HTTP_NOT_FOUND;
143
144         } else {
145
146                 if( 0 && (cookies = apacheParseCookies(r)) ) {
147                         const char* authtoken = apr_table_get(cookies, "ses");
148                         osrfLogInfo(OSRF_LOG_MARK, "SESSION = %s", authtoken);
149                 }
150
151
152                 osrfLogInfo( OSRF_LOG_MARK,  "service=%s, method=%s", service, method );
153                 osrfAppSession* session = osrf_app_client_session_init(service);
154                 double starttime = get_timestamp_millis();
155                 int req_id = osrf_app_session_make_req( session, NULL, method, api_level, mparams );
156                 osrf_message* omsg = NULL;
157
158                 int statuscode = 200;
159
160                 /* kick off the object */
161                 if (isXML)
162                         ap_rputs("<response xmlns=\"http://opensrf.org/-/namespaces/gateway/v1\"><payload>", r);
163                 else
164                         ap_rputs("{\"payload\":[", r);
165
166                 int morethan1           = 0;
167                 char* statusname        = NULL;
168                 char* statustext        = NULL;
169                 char* output            = NULL;
170
171                 while((omsg = osrfAppSessionRequestRecv( session, req_id, 60 ))) {
172         
173                         statuscode = omsg->status_code;
174                         jsonObject* res;        
175
176                         if( ( res = osrfMessageGetResult(omsg)) ) {
177
178                                 if (isXML) {
179                                         output = jsonObjectToXML( res );
180                                 } else {
181                                         output = jsonObjectToJSON( res );
182                                         if( morethan1 ) ap_rputs(",", r); /* comma between JSON array items */
183                                 }
184                                 ap_rputs(output, r);
185                                 free(output);
186                                 morethan1 = 1;
187                 
188                         } else {
189         
190                                 if( statuscode > 299 ) { /* the request returned a low level error */
191                                         statusname = omsg->status_name ? strdup(omsg->status_name) : strdup("Unknown Error");
192                                         statustext = omsg->status_text ? strdup(omsg->status_text) : strdup("No Error Message");
193                                         osrfLogError( OSRF_LOG_MARK,  "Gateway received error: %s", statustext );
194                                 }
195                         }
196         
197                         osrf_message_free(omsg);
198                         if(statusname) break;
199                 }
200
201                 double duration = get_timestamp_millis() - starttime;
202                 osrfLogDebug(OSRF_LOG_MARK, "gateway request took %lf seconds", duration);
203
204
205                 if (isXML)
206                         ap_rputs("</payload>", r);
207                 else
208                         ap_rputs("]",r); /* finish off the payload array */
209
210                 if(statusname) {
211
212                         /* add a debug field if the request died */
213                         ap_log_rerror( APLOG_MARK, APLOG_INFO, 0, r, 
214                                         "OpenSRF JSON Request returned error: %s -> %s", statusname, statustext );
215                         int l = strlen(statusname) + strlen(statustext) + 32;
216                         char buf[l];
217                         bzero(buf,l);
218
219                         if (isXML)
220                                 snprintf( buf, l, "<debug>\"%s : %s\"</debug>", statusname, statustext );
221
222                         else {
223                                 char bb[l];
224                                 bzero(bb, l);
225                                 snprintf(bb, l,  "%s : %s", statusname, statustext);
226                                 jsonObject* tmp = jsonNewObject(bb);
227                                 char* j = jsonObjectToJSON(tmp);
228                                 snprintf( buf, l, ",\"debug\": %s", j);
229                                 free(j);
230                                 jsonObjectFree(tmp);
231                         }
232
233                         ap_rputs(buf, r);
234
235                         free(statusname);
236                         free(statustext);
237                 }
238
239                 /* insert the status code */
240                 char buf[32];
241                 bzero(buf,32);
242
243                 if (isXML)
244                         snprintf(buf, 32, "<status>%d</status>", statuscode );
245                 else
246                         snprintf(buf, 32, ",\"status\":%d", statuscode );
247
248                 ap_rputs( buf, r );
249
250                 if (isXML)
251                         ap_rputs("</response>", r);
252                 else
253                         ap_rputs( "}", r ); /* finish off the object */
254
255                 osrf_app_session_destroy(session);
256         }
257
258         osrfLogInfo(OSRF_LOG_MARK, "Completed processing service=%s, method=%s", service, method);
259         string_array_destroy(params);
260         string_array_destroy(mparams);
261
262         osrfLogDebug(OSRF_LOG_MARK, "Gateway served %d requests", ++numserved);
263
264         return ret;
265 }
266
267
268 #ifdef OSRF_GATEWAY_NASTY_DEBUG
269 /* --------------------------------------------------------------------- */
270 /* DEBUG HOOKS */
271 static int osrf_dbg_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp){
272         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: osrf_dbg_pre_config hook");
273         return OK;
274 }
275 static int osrf_dbg_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s) {
276         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: osrf_dbg_post_config hook");
277         return OK;
278 }
279 static int osrf_dbg_open_logs(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s) {
280         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: osrf_dbg_open_logs hook");
281         return OK;
282 }
283 static int osrf_dbg_quick_handler(request_rec *r, int lookup_uri) {
284         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: osrf_dbg_quick_handler hook");
285         return DECLINED;
286 }
287 static int osrf_dbg_pre_connection(conn_rec *c, void *csd) {
288         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: osrf_dbg_pre_connection hook");
289         return OK;
290 }
291 static int osrf_dbg_process_connection(conn_rec *c) {
292         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: osrf_dbg_process_connection hook");
293         return DECLINED;
294 }
295 static int osrf_dbg_post_read_request(request_rec *r) {
296         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: osrf_dbg_read_request hook");
297         return DECLINED;
298 }
299 static int osrf_dbg_logger(request_rec *r) {
300         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: osrf_dbg_dbg_logger hook");
301         return DECLINED;
302 }
303 static int osrf_dbg_translate_handler(request_rec *r) {
304         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: osrf_dbg_translate_handler hook");
305         return DECLINED;
306 }
307 static int osrf_dbg_header_parser_handler(request_rec *r) {
308         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: osrf_dbg_header_parser_handler hook");
309         return DECLINED;
310 }
311 static int osrf_dbg_check_user_id(request_rec *r) {
312         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: osrf_dbg_check_user_id hook");
313         return DECLINED;
314 }
315 static int osrf_dbg_fixer_upper(request_rec *r) {
316         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: osrf_dbg_fixer_upper hook");
317         return OK;
318 }
319 static int osrf_dbg_type_checker(request_rec *r) {
320         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: osrf_dbg_type_checker hook");
321         return DECLINED;
322 }
323 static int osrf_dbg_access_checker(request_rec *r) {
324         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: osrf_dbg_access_checker hook");
325         return DECLINED;
326 }
327 static int osrf_dbg_auth_checker(request_rec *r) {
328         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: osrf_dbg_auth_checker hook");
329         return DECLINED;
330 }
331 static void osrf_dbg_insert_filter(request_rec *r) {
332         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: osrf_dbg_insert_filter hook");
333 }
334 /* --------------------------------------------------------------------- */
335 #endif
336
337
338 static void osrf_json_gateway_register_hooks (apr_pool_t *p) {
339         ap_hook_handler(osrf_json_gateway_method_handler, NULL, NULL, APR_HOOK_MIDDLE);
340         ap_hook_child_init(osrf_json_gateway_child_init,NULL,NULL,APR_HOOK_MIDDLE);
341
342 #ifdef OSRF_GATEWAY_NASTY_DEBUG
343         ap_hook_pre_config(osrf_dbg_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
344         ap_hook_post_config(osrf_dbg_post_config, NULL, NULL, APR_HOOK_MIDDLE);
345         ap_hook_open_logs(osrf_dbg_open_logs, NULL, NULL, APR_HOOK_MIDDLE);
346         ap_hook_quick_handler(osrf_dbg_quick_handler, NULL, NULL, APR_HOOK_MIDDLE);
347         ap_hook_pre_connection(osrf_dbg_pre_connection, NULL, NULL, APR_HOOK_MIDDLE);
348         ap_hook_process_connection(osrf_dbg_process_connection, NULL, NULL, APR_HOOK_MIDDLE);
349         ap_hook_post_read_request(osrf_dbg_post_read_request, NULL, NULL, APR_HOOK_MIDDLE);
350         ap_hook_log_transaction(osrf_dbg_logger, NULL, NULL, APR_HOOK_MIDDLE);
351         ap_hook_translate_name(osrf_dbg_translate_handler, NULL, NULL, APR_HOOK_MIDDLE);
352         ap_hook_header_parser(osrf_dbg_header_parser_handler, NULL, NULL, APR_HOOK_MIDDLE);
353         ap_hook_check_user_id(osrf_dbg_check_user_id, NULL, NULL, APR_HOOK_MIDDLE);
354         ap_hook_fixups(osrf_dbg_fixer_upper, NULL, NULL, APR_HOOK_MIDDLE);
355         ap_hook_type_checker(osrf_dbg_type_checker, NULL, NULL, APR_HOOK_MIDDLE);
356         ap_hook_access_checker(osrf_dbg_access_checker, NULL, NULL, APR_HOOK_MIDDLE);
357         ap_hook_auth_checker(osrf_dbg_auth_checker, NULL, NULL, APR_HOOK_MIDDLE);
358         ap_hook_insert_filter(osrf_dbg_insert_filter, NULL, NULL, APR_HOOK_MIDDLE);
359 #endif
360 }
361
362
363 module AP_MODULE_DECLARE_DATA osrf_json_gateway_module = {
364         STANDARD20_MODULE_STUFF,
365         NULL,
366         NULL,
367         osrf_json_gateway_create_config,
368         NULL,
369         osrf_json_gateway_cmds,
370         osrf_json_gateway_register_hooks,
371 };
372
373
374
375