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