]> git.evergreen-ils.org Git - Evergreen.git/blob - OpenSRF/src/srfsh/srfsh.c
incorporated ilseents.xml file into opac
[Evergreen.git] / OpenSRF / src / srfsh / srfsh.c
1 #include "srfsh.h"
2
3 int is_from_script = 0;
4 FILE* shell_writer = NULL;
5 FILE* shell_reader = NULL;
6
7 int main( int argc, char* argv[] ) {
8
9         /* --------------------------------------------- */
10         /* see if they have a .srfsh.xml in their home directory */
11         char* home = getenv("HOME");
12         int l = strlen(home) + 36;
13         char fbuf[l];
14         memset(fbuf, 0, l);
15         sprintf(fbuf,"%s/.srfsh.xml",home);
16         
17         //osrfLogInit( OSRF_LOG_TYPE_SYSLOG, "srfsh", 
18
19         if(!access(fbuf, R_OK)) {
20                 if( ! osrf_system_bootstrap_client(fbuf, "srfsh") ) {
21                         osrfLogError( "Unable to bootstrap client for requests");
22                         return -1;
23                 }
24
25         } else {
26                 osrfLogError( "No Config file found at %s", fbuf );
27                 return -1;
28         }
29
30         if(argc > 1) {
31                 /* for now.. the first arg is used as a script file for processing */
32                 int f;
33                 if( (f = open(argv[1], O_RDONLY)) == -1 ) {
34                         osrfLogError("Unable to open file %s for reading, exiting...", argv[1]);
35                         return -1;
36                 }
37
38                 if(dup2(f, STDIN_FILENO) == -1) {
39                         osrfLogError("Unable to duplicate STDIN, exiting...");
40                         return -1;
41                 }
42
43                 close(f);
44                 is_from_script = 1;
45         }
46                 
47         /* --------------------------------------------- */
48         load_history();
49
50
51         client = osrf_system_get_transport_client();
52
53         /* open the shell handle */
54         shell_writer = popen( "bash", "w");
55         //shell_reader = popen( "bash", "r");
56
57         /* main process loop */
58         char* request;
59         while((request=readline(prompt))) {
60
61                 if( !strcmp(request, "exit") || !strcmp(request,"quit")) 
62                         break; 
63
64                 char* req_copy = strdup(request);
65
66                 parse_request( req_copy ); 
67                 if( request && strlen(request) > 1 ) {
68                         add_history(request);
69                 }
70
71                 free(request);
72                 free(req_copy);
73
74                 fflush(shell_writer);
75                 fflush(stderr);
76                 fflush(stdout);
77         }
78
79         if(history_file != NULL )
80                 write_history(history_file);
81
82         free(request);
83
84         osrf_system_shutdown();
85         return 0;
86 }
87
88 void sig_child_handler( int s ) {
89         child_dead = 1;
90 }
91
92 /*
93 void sig_int_handler( int s ) {
94         printf("\n");
95         caught_sigint = 1;
96         signal(SIGINT,sig_int_handler);
97 }
98 */
99
100 int load_history() {
101
102         char* home = getenv("HOME");
103         int l = strlen(home) + 24;
104         char fbuf[l];
105
106         memset(fbuf, 0, l);
107         sprintf(fbuf,"%s/.srfsh_history",home);
108         history_file = strdup(fbuf);
109
110         if(!access(history_file, W_OK | R_OK )) {
111                 history_length = 999;
112                 read_history(history_file);
113         }
114         return 1;
115 }
116
117
118 int parse_error( char* words[] ) {
119
120         if( ! words )
121                 return 0;
122
123
124         int i = 0;
125         char* current;
126         char buffer[256];
127         memset(buffer, 0, 256);
128         while( (current=words[i++]) ) {
129                 strcat(buffer, current);
130                 strcat(buffer, " ");
131         }
132         if( ! buffer || strlen(buffer) < 1 ) 
133                 printf("\n");
134
135         fprintf( stderr, "???: %s\n", buffer );
136         return 0;
137
138 }
139
140
141 int parse_request( char* request ) {
142
143         if( request == NULL )
144                 return 0;
145
146         int ret_val = 0;
147         int i = 0;
148         char* words[COMMAND_BUFSIZE]; 
149         memset(words,0,COMMAND_BUFSIZE);
150         char* req = request;
151
152         char* cur_tok = strtok( req, " " );
153
154         if( cur_tok == NULL )
155                 return 0;
156
157         while(cur_tok != NULL) {
158                 words[i++] = cur_tok;
159                 cur_tok = strtok( NULL, " " );
160         }
161
162
163         // not sure why (strtok?), but this is necessary
164         memset( words + i, 0, COMMAND_BUFSIZE - i );
165
166         /* pass off to the top level command */
167         if( !strcmp(words[0],"router") ) 
168                 ret_val = handle_router( words );
169
170         /*
171         else if( !strcmp(words[0],"time") ) 
172                 ret_val = handle_time( words );
173                 */
174
175         else if (!strcmp(words[0],"request"))
176                 ret_val = handle_request( words, 0 );
177
178         else if (!strcmp(words[0],"relay"))
179                 ret_val = handle_request( words, 1 );
180
181         else if (!strcmp(words[0],"help"))
182                 ret_val = print_help();
183
184         else if (!strcmp(words[0],"set"))
185                 ret_val = handle_set(words);
186
187         else if (!strcmp(words[0],"print"))
188                 ret_val = handle_print(words);
189
190         else if (!strcmp(words[0],"math_bench"))
191                 ret_val = handle_math(words);
192
193         else if (!strcmp(words[0],"introspect"))
194                 ret_val = handle_introspect(words);
195
196         else if (!strcmp(words[0],"login"))
197                 ret_val = handle_login(words);
198
199         else if (words[0][0] == '!')
200                 ret_val = handle_exec( words, 1 );
201
202         if(!ret_val) {
203                 #ifdef EXEC_DEFAULT
204                         return handle_exec( words, 0 );
205                 #else
206                         return parse_error( words );
207                 #endif
208         }
209
210         return 1;
211
212 }
213
214
215 int handle_introspect(char* words[]) {
216
217         if(words[1] && words[2]) {
218                 fprintf(stderr, "--> %s\n", words[1]);
219                 char buf[256];
220                 memset(buf,0,256);
221                 sprintf( buf, "request %s opensrf.system.method %s", words[1], words[2] );
222                 return parse_request( buf );
223
224         } else {
225         
226                 if(words[1]) {
227                         fprintf(stderr, "--> %s\n", words[1]);
228                         char buf[256];
229                         memset(buf,0,256);
230                         sprintf( buf, "request %s opensrf.system.method.all", words[1] );
231                         return parse_request( buf );
232                 }
233         }
234
235         return 0;
236 }
237
238
239 int handle_login( char* words[]) {
240
241         if( words[1] && words[2]) {
242
243                 char* username = words[1];
244                 char* password = words[2];
245
246                 char buf[256];
247                 memset(buf,0,256);
248
249                 char buf2[256];
250                 memset(buf2,0,256);
251
252                 sprintf( buf, 
253                                 "request open-ils.auth open-ils.auth.authenticate.init \"%s\"", username );
254                 parse_request(buf); 
255
256                 char* hash;
257                 if(last_result && last_result->_result_content) {
258                         jsonObject* r = last_result->_result_content;
259                         hash = jsonObjectGetString(r);
260                 } else return 0;
261
262
263                 char* pass_buf = md5sum(password);
264
265                 char both_buf[256];
266                 memset(both_buf,0,256);
267                 sprintf(both_buf,"%s%s",hash, pass_buf);
268
269                 char* mess_buf = md5sum(both_buf);
270
271                 sprintf( buf2,
272                                 "request open-ils.auth open-ils.auth.authenticate.complete \"%s\", \"%s\", \"opac\"", 
273                                 username, mess_buf );
274
275                 free(pass_buf);
276                 free(mess_buf);
277
278                 parse_request( buf2 );
279
280                 jsonObject* x = last_result->_result_content;
281                 if(x) {
282                         char* authtoken = jsonObjectGetString(jsonObjectGetKey(x, "authtoken"));
283                         if(authtoken) login_session = strdup(authtoken);
284                         else login_session = NULL;
285                 }
286                 else login_session = NULL;
287
288                 printf("Login Session: %s\n", login_session );
289                 
290                 return 1;
291
292         }
293
294         return 0;
295 }
296
297 int handle_set( char* words[]) {
298
299         char* variable;
300         if( (variable=words[1]) ) {
301
302                 char* val;
303                 if( (val=words[2]) ) {
304
305                         if(!strcmp(variable,"pretty_print")) {
306                                 if(!strcmp(val,"true")) {
307                                         pretty_print = 1;
308                                         printf("pretty_print = true\n");
309                                         return 1;
310                                 } 
311                                 if(!strcmp(val,"false")) {
312                                         pretty_print = 0;
313                                         printf("pretty_print = false\n");
314                                         return 1;
315                                 } 
316                         }
317
318                         if(!strcmp(variable,"raw_print")) {
319                                 if(!strcmp(val,"true")) {
320                                         raw_print = 1;
321                                         printf("raw_print = true\n");
322                                         return 1;
323                                 } 
324                                 if(!strcmp(val,"false")) {
325                                         raw_print = 0;
326                                         printf("raw_print = false\n");
327                                         return 1;
328                                 } 
329                         }
330
331                 }
332         }
333
334         return 0;
335 }
336
337
338 int handle_print( char* words[]) {
339
340         char* variable;
341         if( (variable=words[1]) ) {
342                 if(!strcmp(variable,"pretty_print")) {
343                         if(pretty_print) {
344                                 printf("pretty_print = true\n");
345                                 return 1;
346                         } else {
347                                 printf("pretty_print = false\n");
348                                 return 1;
349                         }
350                 }
351
352                 if(!strcmp(variable,"login")) {
353                         printf("login session = %s\n", login_session );
354                         return 1;
355                 }
356
357         }
358         return 0;
359 }
360
361 int handle_router( char* words[] ) {
362
363         if(!client)
364                 return 1;
365
366         int i;
367
368         if( words[1] ) { 
369                 if( !strcmp(words[1],"query") ) {
370                         
371                         if( words[2] && !strcmp(words[2],"servers") ) {
372                                 for(i=3; i < COMMAND_BUFSIZE - 3 && words[i]; i++ ) {   
373                                         router_query_servers( words[i] );
374                                 }
375                                 return 1;
376                         }
377                         return 0;
378                 }
379                 return 0;
380         }
381         return 0;
382 }
383
384
385 /* if new shell, spawn a new child and subshell to do the work,
386         otherwise pipe the request to the currently open (piped) shell */
387 int handle_exec(char* words[], int new_shell) {
388
389         if(!words[0]) return 0;
390
391         if( words[0] && words[0][0] == '!') {
392                 int len = strlen(words[0]);
393                 char command[len];
394                 memset(command,0,len);
395         
396                 int i; /* chop out the ! */
397                 for( i=1; i!= len; i++) {
398                         command[i-1] = words[0][i];
399                 }
400         
401                 free(words[0]);
402                 words[0] = strdup(command);
403         }
404
405         if(new_shell) {
406                 signal(SIGCHLD, sig_child_handler);
407
408                 if(fork()) {
409         
410                         waitpid(-1, 0, 0);
411                         if(child_dead) {
412                                 signal(SIGCHLD,sig_child_handler);
413                                 child_dead = 0;
414                         }
415         
416                 } else {
417                         execvp( words[0], words );
418                         exit(0);
419                 }
420
421         } else {
422
423
424                 growing_buffer* b = buffer_init(64);
425                 int i = 0;
426                 while(words[i]) 
427                         buffer_fadd( b, "%s ", words[i++] );
428         
429                 buffer_add( b, "\n");
430         
431                 //int reader;
432                 //int reader = dup2(STDOUT_FILENO, reader);
433                 //int reader = dup(STDOUT_FILENO);
434                 //close(STDOUT_FILENO);
435
436                 fprintf( shell_writer, b->buf );
437                 buffer_free(b);
438         
439                 fflush(shell_writer);
440                 usleep(1000);
441
442                 /*
443                 char c[4096];
444                 bzero(c, 4096);
445                 read( reader, c, 4095 );
446                 fprintf(stderr, "read %s", c);
447                 dup2(reader, STDOUT_FILENO);
448                 */
449
450         }
451
452         
453         return 1;
454 }
455
456
457 int handle_request( char* words[], int relay ) {
458
459         if(!client)
460                 return 1;
461
462         if(words[1]) {
463                 char* server = words[1];
464                 char* method = words[2];
465                 int i;
466                 growing_buffer* buffer = NULL;
467                 if(!relay) {
468                         buffer = buffer_init(128);
469                         buffer_add(buffer, "[");
470                         for(i = 3; words[i] != NULL; i++ ) {
471                                 /* removes trailing semicolon if user accidentally enters it */
472                                 if( words[i][strlen(words[i])-1] == ';' )
473                                         words[i][strlen(words[i])-1] = '\0';
474                                 buffer_add( buffer, words[i] );
475                                 buffer_add(buffer, " ");
476                         }
477                         buffer_add(buffer, "]");
478                 }
479
480                 return send_request( server, method, buffer, relay );
481         } 
482
483         return 0;
484 }
485
486 int send_request( char* server, 
487                 char* method, growing_buffer* buffer, int relay ) {
488         if( server == NULL || method == NULL )
489                 return 0;
490
491         jsonObject* params = NULL;
492         if( !relay ) {
493                 if( buffer != NULL && buffer->n_used > 0 ) 
494                         params = json_parse_string(buffer->buf);
495         } else {
496                 if(!last_result || ! last_result->_result_content) { 
497                         printf("We're not going to call 'relay' with no result params\n");
498                         return 1;
499                 }
500                 else {
501                         jsonObject* o = jsonNewObject(NULL);
502                         jsonObjectPush(o, last_result->_result_content );
503                         params = o;
504                 }
505         }
506
507
508         if(buffer->n_used > 0 && params == NULL) {
509                 fprintf(stderr, "JSON error detected, not executing\n");
510                 return 1;
511         }
512
513         osrf_app_session* session = osrf_app_client_session_init(server);
514
515         if(!osrf_app_session_connect(session)) {
516                 osrfLogWarning( "Unable to connect to remote service %s\n", server );
517                 return 1;
518         }
519
520         double start = get_timestamp_millis();
521         //int req_id = osrf_app_session_make_request( session, params, method, 1, NULL );
522         int req_id = osrf_app_session_make_req( session, params, method, 1, NULL );
523
524
525         osrf_message* omsg = osrf_app_session_request_recv( session, req_id, 60 );
526
527         if(!omsg) 
528                 printf("\nReceived no data from server\n");
529         
530         
531         signal(SIGPIPE, SIG_IGN);
532
533         FILE* less; 
534         if(!is_from_script) less = popen( "less -EX", "w");
535         else less = stdout;
536
537         if( less == NULL ) { less = stdout; }
538
539         growing_buffer* resp_buffer = buffer_init(4096);
540
541         while(omsg) {
542
543                 if(raw_print) {
544
545                         if(omsg->_result_content) {
546         
547                                 osrf_message_free(last_result);
548                                 last_result = omsg;
549         
550                                 char* content;
551         
552                                 if( pretty_print && omsg->_result_content ) {
553                                         char* j = jsonObjectToJSON(omsg->_result_content);
554                                         //content = json_printer(j); 
555                                         content = jsonFormatString(j);
556                                         free(j);
557                                 } else
558                                         content = jsonObjectGetString(omsg->_result_content);
559         
560                                 printf( "\nReceived Data: %s\n", content ); 
561                                 free(content);
562         
563                         } else {
564
565                                 char code[16];
566                                 memset(code, 0, 16);
567                                 sprintf( code, "%d", omsg->status_code );
568                                 buffer_add( resp_buffer, code );
569
570                                 printf( "\nReceived Exception:\nName: %s\nStatus: %s\nStatus: %s\n", 
571                                                 omsg->status_name, omsg->status_text, code );
572
573                                 fflush(stdout);
574                         }
575
576                 } else {
577
578                         if(omsg->_result_content) {
579         
580                                 osrf_message_free(last_result);
581                                 last_result = omsg;
582         
583                                 char* content;
584         
585                                 if( pretty_print && omsg->_result_content ) {
586                                         char* j = jsonObjectToJSON(omsg->_result_content);
587                                         //content = json_printer(j); 
588                                         content = jsonFormatString(j);
589                                         free(j);
590                                 } else
591                                         content = jsonObjectGetString(omsg->_result_content);
592         
593                                 buffer_add( resp_buffer, "\nReceived Data: " ); 
594                                 buffer_add( resp_buffer, content );
595                                 buffer_add( resp_buffer, "\n" );
596                                 free(content);
597         
598                         } else {
599         
600                                 buffer_add( resp_buffer, "\nReceived Exception:\nName: " );
601                                 buffer_add( resp_buffer, omsg->status_name );
602                                 buffer_add( resp_buffer, "\nStatus: " );
603                                 buffer_add( resp_buffer, omsg->status_text );
604                                 buffer_add( resp_buffer, "\nStatus: " );
605                                 char code[16];
606                                 memset(code, 0, 16);
607                                 sprintf( code, "%d", omsg->status_code );
608                                 buffer_add( resp_buffer, code );
609                         }
610                 }
611
612
613                 omsg = osrf_app_session_request_recv( session, req_id, 5 );
614
615         }
616
617         double end = get_timestamp_millis();
618
619         fprintf( less, resp_buffer->buf );
620         buffer_free( resp_buffer );
621         fprintf( less, "\n------------------------------------\n");
622         if( osrf_app_session_request_complete( session, req_id ))
623                 fprintf(less, "Request Completed Successfully\n");
624
625
626         fprintf(less, "Request Time in seconds: %.6f\n", end - start );
627         fprintf(less, "------------------------------------\n");
628
629         pclose(less); 
630
631         osrf_app_session_request_finish( session, req_id );
632         osrf_app_session_disconnect( session );
633         osrf_app_session_destroy( session );
634
635
636         return 1;
637
638
639 }
640
641 /*
642 int handle_time( char* words[] ) {
643
644         if( ! words[1] ) {
645
646                 char buf[36];
647                 memset(buf,0,36);
648                 get_timestamp(buf);
649                 printf( "%s\n", buf );
650                 return 1;
651         }
652
653         if( words[1] ) {
654                 time_t epoch = (time_t)atoi( words[1] );
655                 char* localtime = strdup( ctime( &epoch ) );
656                 printf( "%s => %s", words[1], localtime );
657                 free(localtime);
658                 return 1;
659         }
660
661         return 0;
662
663 }
664 */
665
666                 
667
668 int router_query_servers( char* router_server ) {
669
670         if( ! router_server || strlen(router_server) == 0 ) 
671                 return 0;
672
673         char rbuf[256];
674         memset(rbuf,0,256);
675         sprintf(rbuf,"router@%s/router", router_server );
676                 
677         transport_message* send = 
678                 message_init( "servers", NULL, NULL, rbuf, NULL );
679         message_set_router_info( send, NULL, NULL, NULL, "query", 0 );
680
681         client_send_message( client, send );
682         message_free( send );
683
684         transport_message* recv = client_recv( client, -1 );
685         if( recv == NULL ) {
686                 fprintf(stderr, "NULL message received from router\n");
687                 return 1;
688         }
689         
690         printf( 
691                         "---------------------------------------------------------------------------------\n"
692                         "Received from 'server' query on %s\n"
693                         "---------------------------------------------------------------------------------\n"
694                         "original reg time | latest reg time | last used time | class | server\n"
695                         "---------------------------------------------------------------------------------\n"
696                         "%s"
697                         "---------------------------------------------------------------------------------\n"
698                         , router_server, recv->body );
699
700         message_free( recv );
701         
702         return 1;
703 }
704                 
705 int print_help() {
706
707         printf(
708                         "---------------------------------------------------------------------------------\n"
709                         "Commands:\n"
710                         "---------------------------------------------------------------------------------\n"
711                         "help                   - Display this message\n"
712                         "!<command> [args] - Forks and runs the given command in the shell\n"
713                         "time                   - Prints the current time\n"                                    
714                         "time <timestamp>       - Formats seconds since epoch into readable format\n"   
715                         "set <variable> <value> - set a srfsh variable (e.g. set pretty_print true )\n"
716                         "print <variable>               - Displays the value of a srfsh variable\n"
717                         "---------------------------------------------------------------------------------\n"
718
719                         "router query servers <server1 [, server2, ...]>\n"
720                         "       - Returns stats on connected services\n"
721                         "\n"
722                         "\n"
723                         "request <service> <method> [ <json formatted string of params> ]\n"
724                         "       - Anything passed in will be wrapped in a json array,\n"
725                         "               so add commas if there is more than one param\n"
726                         "\n"
727                         "\n"
728                         "relay <service> <method>\n"
729                         "       - Performs the requested query using the last received result as the param\n"
730                         "\n"
731                         "\n"
732                         "math_bench <num_batches> [0|1|2]\n"
733                         "       - 0 means don't reconnect, 1 means reconnect after each batch of 4, and\n"
734                         "                2 means reconnect after every request\n"
735                         "\n"
736                         "introspect <service>\n"
737                         "       - prints the API for the service\n"
738                         "\n"
739                         "\n"
740                         "---------------------------------------------------------------------------------\n"
741                         " Commands for Open-ILS\n"
742                         "---------------------------------------------------------------------------------\n"
743                         "login <username> <password>\n"
744                         "       -       Logs into the 'server' and displays the session id\n"
745                         "       - To view the session id later, enter: print login\n"
746                         "---------------------------------------------------------------------------------\n"
747                         "\n"
748                         "\n"
749                         "Note: long output is piped through 'less'.  To search in 'less', type: /<search>\n"
750                         "---------------------------------------------------------------------------------\n"
751                         "\n"
752                         );
753
754         return 1;
755 }
756
757
758
759 char* tabs(int count) {
760         growing_buffer* buf = buffer_init(24);
761         int i;
762         for(i=0;i!=count;i++)
763                 buffer_add(buf, "  ");
764
765         char* final = buffer_data( buf );
766         buffer_free( buf );
767         return final;
768 }
769
770 int handle_math( char* words[] ) {
771         if( words[1] )
772                 return do_math( atoi(words[1]), 0 );
773         return 0;
774 }
775
776
777 int do_math( int count, int style ) {
778
779         osrf_app_session* session = osrf_app_client_session_init(  "opensrf.math" );
780
781         jsonObject* params = json_parse_string("[]");
782         jsonObjectPush(params,jsonNewObject("1"));
783         jsonObjectPush(params,jsonNewObject("2"));
784
785         char* methods[] = { "add", "sub", "mult", "div" };
786         char* answers[] = { "3", "-1", "2", "0.500000" };
787
788         float times[ count * 4 ];
789         memset(times,0,count*4);
790
791         int k;
792         for(k=0;k!=100;k++) {
793                 if(!(k%10)) 
794                         fprintf(stderr,"|");
795                 else
796                         fprintf(stderr,".");
797         }
798
799         fprintf(stderr,"\n\n");
800
801         int running = 0;
802         int i;
803         for(i=0; i!= count; i++) {
804
805                 int j;
806                 for(j=0; j != 4; j++) {
807
808                         ++running;
809
810                         double start = get_timestamp_millis();
811                         int req_id = osrf_app_session_make_req( session, params, methods[j], 1, NULL );
812                         osrf_message* omsg = osrf_app_session_request_recv( session, req_id, 5 );
813                         double end = get_timestamp_millis();
814
815                         times[(4*i) + j] = end - start;
816
817                         if(omsg) {
818         
819                                 if(omsg->_result_content) {
820                                         char* jsn = jsonObjectToJSON(omsg->_result_content);
821                                         if(!strcmp(jsn, answers[j]))
822                                                 fprintf(stderr, "+");
823                                         else
824                                                 fprintf(stderr, "\n![%s] - should be %s\n", jsn, answers[j] );
825                                         free(jsn);
826                                 }
827
828
829                                 osrf_message_free(omsg);
830                 
831                         } else { fprintf( stderr, "\nempty message for tt: %d\n", req_id ); }
832
833                         osrf_app_session_request_finish( session, req_id );
834
835                         if(style == 2)
836                                 osrf_app_session_disconnect( session );
837
838                         if(!(running%100))
839                                 fprintf(stderr,"\n");
840                 }
841
842                 if(style==1)
843                         osrf_app_session_disconnect( session );
844         }
845
846         osrf_app_session_destroy( session );
847         jsonObjectFree(params);
848
849         int c;
850         float total = 0;
851         for(c=0; c!= count*4; c++) 
852                 total += times[c];
853
854         float avg = total / (count*4); 
855         fprintf(stderr, "\n      Average round trip time: %f\n", avg );
856
857         return 1;
858 }