]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/gateway/osrf_json_gateway.c
logging all requests + params to activity log
[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                 ap_log_error( APLOG_MARK, APLOG_DEBUG, 0, s, 
71                         "allowed service: %s\n", osrfStringArrayGetString(allowedServices, i));
72         }
73 }
74
75 static int osrf_json_gateway_method_handler (request_rec *r) {
76
77         /* make sure we're needed first thing*/
78         if (strcmp(r->handler, MODULE_NAME )) return DECLINED;
79
80         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: entered request handler");
81
82         /* verify we are connected */
83         if( !bootstrapped || !osrf_system_get_transport_client()) {
84                 ap_log_rerror( APLOG_MARK, APLOG_ERR, 0, r, "Cannot process request "
85                                 "because the OpenSRF JSON gateway has not been bootstrapped...");
86                 return HTTP_INTERNAL_SERVER_ERROR;
87         }
88
89         osrfLogSetAppname("osrf_json_gw");
90
91         char* service           = NULL; /* service to connect to */
92         char* method            = NULL; /* method to perform */
93         char* format            = NULL; /* method to perform */
94         char* a_l                       = NULL; /* request api level */
95         int   isXML                     = 0;
96         int   api_level = 1;
97
98         r->allowed |= (AP_METHOD_BIT << M_GET);
99         r->allowed |= (AP_METHOD_BIT << M_POST);
100
101         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: parsing URL params");
102         string_array* mparams   = NULL;
103         string_array* params            = apacheParseParms(r); /* free me */
104         service         = apacheGetFirstParamValue( params, "service" );
105         method          = apacheGetFirstParamValue( params, "method" ); 
106         format          = apacheGetFirstParamValue( params, "format" ); 
107         a_l                     = apacheGetFirstParamValue( params, "api_level" ); 
108         mparams         = apacheGetParamValues( params, "param" ); /* free me */
109
110         if (a_l)
111                 api_level = atoi(a_l);
112
113         if (format && !strcasecmp(format, "xml" )) {
114                 isXML = 1;
115                 ap_set_content_type(r, "application/xml");
116         } else {
117                 ap_set_content_type(r, "text/plain");
118         }
119
120         int ret = OK;
121
122         if(!(service && method) || 
123                 !osrfStringArrayContains(allowedServices, service)) {
124
125                 osrfLogError(OSRF_LOG_MARK, 
126                         "Service [%s] not found or not allowed", service);
127                 ret = HTTP_NOT_FOUND;
128
129         } else {
130
131                 /* ----------------------------------------------------------------- */
132                 /* log all requests to the activity log */
133                 growing_buffer* act = buffer_init(128); 
134                 buffer_fadd(act, "[%s] %s:%s", r->connection->remote_ip, service, method );
135                 char* str; int i = 0;
136                 while( (str = osrfStringArrayGetString(mparams, i++)) ) 
137                         buffer_fadd(act, " %s", str);
138
139                 osrfLogActivity( OSRF_LOG_MARK, act->buf );
140                 buffer_free(act);
141                 /* ----------------------------------------------------------------- */
142
143                 osrfAppSession* session = osrf_app_client_session_init(service);
144
145                 double starttime = get_timestamp_millis();
146                 int req_id = osrf_app_session_make_req( session, NULL, method, api_level, mparams );
147                 osrf_message* omsg = NULL;
148
149                 int statuscode = 200;
150
151                 /* kick off the object */
152                 if (isXML)
153                         ap_rputs("<response xmlns=\"http://opensrf.org/-/namespaces/gateway/v1\"><payload>", r);
154                 else
155                         ap_rputs("{\"payload\":[", r);
156
157                 int morethan1           = 0;
158                 char* statusname        = NULL;
159                 char* statustext        = NULL;
160                 char* output            = NULL;
161
162                 while((omsg = osrfAppSessionRequestRecv( session, req_id, 60 ))) {
163         
164                         statuscode = omsg->status_code;
165                         jsonObject* res;        
166
167                         if( ( res = osrfMessageGetResult(omsg)) ) {
168
169                                 if (isXML) {
170                                         output = jsonObjectToXML( res );
171                                 } else {
172                                         output = jsonObjectToJSON( res );
173                                         if( morethan1 ) ap_rputs(",", r); /* comma between JSON array items */
174                                 }
175                                 ap_rputs(output, r);
176                                 free(output);
177                                 morethan1 = 1;
178                 
179                         } else {
180         
181                                 if( statuscode > 299 ) { /* the request returned a low level error */
182                                         statusname = omsg->status_name ? strdup(omsg->status_name) : strdup("Unknown Error");
183                                         statustext = omsg->status_text ? strdup(omsg->status_text) : strdup("No Error Message");
184                                         osrfLogError( OSRF_LOG_MARK,  "Gateway received error: %s", statustext );
185                                 }
186                         }
187         
188                         osrf_message_free(omsg);
189                         if(statusname) break;
190                 }
191
192                 double duration = get_timestamp_millis() - starttime;
193                 osrfLogDebug(OSRF_LOG_MARK, "gateway request took %lf seconds", duration);
194
195
196                 if (isXML)
197                         ap_rputs("</payload>", r);
198                 else
199                         ap_rputs("]",r); /* finish off the payload array */
200
201                 if(statusname) {
202
203                         /* add a debug field if the request died */
204                         ap_log_rerror( APLOG_MARK, APLOG_INFO, 0, r, 
205                                         "OpenSRF JSON Request returned error: %s -> %s", statusname, statustext );
206                         int l = strlen(statusname) + strlen(statustext) + 32;
207                         char buf[l];
208                         bzero(buf,l);
209
210                         if (isXML)
211                                 snprintf( buf, l, "<debug>\"%s : %s\"</debug>", statusname, statustext );
212
213                         else {
214                                 char bb[l];
215                                 bzero(bb, l);
216                                 snprintf(bb, l,  "%s : %s", statusname, statustext);
217                                 jsonObject* tmp = jsonNewObject(bb);
218                                 char* j = jsonObjectToJSON(tmp);
219                                 snprintf( buf, l, ",\"debug\": %s", j);
220                                 free(j);
221                                 jsonObjectFree(tmp);
222                         }
223
224                         ap_rputs(buf, r);
225
226                         free(statusname);
227                         free(statustext);
228                 }
229
230                 /* insert the status code */
231                 char buf[32];
232                 bzero(buf,32);
233
234                 if (isXML)
235                         snprintf(buf, 32, "<status>%d</status>", statuscode );
236                 else
237                         snprintf(buf, 32, ",\"status\":%d", statuscode );
238
239                 ap_rputs( buf, r );
240
241                 if (isXML)
242                         ap_rputs("</response>", r);
243                 else
244                         ap_rputs( "}", r ); /* finish off the object */
245
246                 osrf_app_session_destroy(session);
247         }
248
249         osrfLogInfo(OSRF_LOG_MARK, "Completed processing service=%s, method=%s", service, method);
250         string_array_destroy(params);
251         string_array_destroy(mparams);
252
253         osrfLogDebug(OSRF_LOG_MARK, "Gateway served %d requests", ++numserved);
254
255         return ret;
256 }
257
258
259
260 static void osrf_json_gateway_register_hooks (apr_pool_t *p) {
261         ap_hook_handler(osrf_json_gateway_method_handler, NULL, NULL, APR_HOOK_MIDDLE);
262         ap_hook_child_init(osrf_json_gateway_child_init,NULL,NULL,APR_HOOK_MIDDLE);
263 }
264
265
266 module AP_MODULE_DECLARE_DATA osrf_json_gateway_module = {
267         STANDARD20_MODULE_STUFF,
268         NULL,
269         NULL,
270         osrf_json_gateway_create_config,
271         NULL,
272         osrf_json_gateway_cmds,
273         osrf_json_gateway_register_hooks,
274 };
275
276
277
278