]> git.evergreen-ils.org Git - Evergreen.git/blob - OpenSRF/src/srfsh/srfsh.c
moved C code to a unified logging framework which currently supports syslogging and...
[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                 char* x = jsonObjectGetString(last_result->_result_content);
281                 if(x) login_session = strdup(x);
282                 else login_session = NULL;
283
284                 printf("Login Session: %s\n", login_session );
285                 
286                 return 1;
287
288         }
289
290         return 0;
291 }
292
293 int handle_set( char* words[]) {
294
295         char* variable;
296         if( (variable=words[1]) ) {
297
298                 char* val;
299                 if( (val=words[2]) ) {
300
301                         if(!strcmp(variable,"pretty_print")) {
302                                 if(!strcmp(val,"true")) {
303                                         pretty_print = 1;
304                                         printf("pretty_print = true\n");
305                                         return 1;
306                                 } 
307                                 if(!strcmp(val,"false")) {
308                                         pretty_print = 0;
309                                         printf("pretty_print = false\n");
310                                         return 1;
311                                 } 
312                         }
313
314                         if(!strcmp(variable,"raw_print")) {
315                                 if(!strcmp(val,"true")) {
316                                         raw_print = 1;
317                                         printf("raw_print = true\n");
318                                         return 1;
319                                 } 
320                                 if(!strcmp(val,"false")) {
321                                         raw_print = 0;
322                                         printf("raw_print = false\n");
323                                         return 1;
324                                 } 
325                         }
326
327                 }
328         }
329
330         return 0;
331 }
332
333
334 int handle_print( char* words[]) {
335
336         char* variable;
337         if( (variable=words[1]) ) {
338                 if(!strcmp(variable,"pretty_print")) {
339                         if(pretty_print) {
340                                 printf("pretty_print = true\n");
341                                 return 1;
342                         } else {
343                                 printf("pretty_print = false\n");
344                                 return 1;
345                         }
346                 }
347
348                 if(!strcmp(variable,"login")) {
349                         printf("login session = %s\n", login_session );
350                         return 1;
351                 }
352
353         }
354         return 0;
355 }
356
357 int handle_router( char* words[] ) {
358
359         if(!client)
360                 return 1;
361
362         int i;
363
364         if( words[1] ) { 
365                 if( !strcmp(words[1],"query") ) {
366                         
367                         if( words[2] && !strcmp(words[2],"servers") ) {
368                                 for(i=3; i < COMMAND_BUFSIZE - 3 && words[i]; i++ ) {   
369                                         router_query_servers( words[i] );
370                                 }
371                                 return 1;
372                         }
373                         return 0;
374                 }
375                 return 0;
376         }
377         return 0;
378 }
379
380
381 /* if new shell, spawn a new child and subshell to do the work,
382         otherwise pipe the request to the currently open (piped) shell */
383 int handle_exec(char* words[], int new_shell) {
384
385         if(!words[0]) return 0;
386
387         if( words[0] && words[0][0] == '!') {
388                 int len = strlen(words[0]);
389                 char command[len];
390                 memset(command,0,len);
391         
392                 int i; /* chop out the ! */
393                 for( i=1; i!= len; i++) {
394                         command[i-1] = words[0][i];
395                 }
396         
397                 free(words[0]);
398                 words[0] = strdup(command);
399         }
400
401         if(new_shell) {
402                 signal(SIGCHLD, sig_child_handler);
403
404                 if(fork()) {
405         
406                         waitpid(-1, 0, 0);
407                         if(child_dead) {
408                                 signal(SIGCHLD,sig_child_handler);
409                                 child_dead = 0;
410                         }
411         
412                 } else {
413                         execvp( words[0], words );
414                         exit(0);
415                 }
416
417         } else {
418
419
420                 growing_buffer* b = buffer_init(64);
421                 int i = 0;
422                 while(words[i]) 
423                         buffer_fadd( b, "%s ", words[i++] );
424         
425                 buffer_add( b, "\n");
426         
427                 //int reader;
428                 //int reader = dup2(STDOUT_FILENO, reader);
429                 //int reader = dup(STDOUT_FILENO);
430                 //close(STDOUT_FILENO);
431
432                 fprintf( shell_writer, b->buf );
433                 buffer_free(b);
434         
435                 fflush(shell_writer);
436                 usleep(1000);
437
438                 /*
439                 char c[4096];
440                 bzero(c, 4096);
441                 read( reader, c, 4095 );
442                 fprintf(stderr, "read %s", c);
443                 dup2(reader, STDOUT_FILENO);
444                 */
445
446         }
447
448         
449         return 1;
450 }
451
452
453 int handle_request( char* words[], int relay ) {
454
455         if(!client)
456                 return 1;
457
458         if(words[1]) {
459                 char* server = words[1];
460                 char* method = words[2];
461                 int i;
462                 growing_buffer* buffer = NULL;
463                 if(!relay) {
464                         buffer = buffer_init(128);
465                         buffer_add(buffer, "[");
466                         for(i = 3; words[i] != NULL; i++ ) {
467                                 /* removes trailing semicolon if user accidentally enters it */
468                                 if( words[i][strlen(words[i])-1] == ';' )
469                                         words[i][strlen(words[i])-1] = '\0';
470                                 buffer_add( buffer, words[i] );
471                                 buffer_add(buffer, " ");
472                         }
473                         buffer_add(buffer, "]");
474                 }
475
476                 return send_request( server, method, buffer, relay );
477         } 
478
479         return 0;
480 }
481
482 int send_request( char* server, 
483                 char* method, growing_buffer* buffer, int relay ) {
484         if( server == NULL || method == NULL )
485                 return 0;
486
487         jsonObject* params = NULL;
488         if( !relay ) {
489                 if( buffer != NULL && buffer->n_used > 0 ) 
490                         params = json_parse_string(buffer->buf);
491         } else {
492                 if(!last_result || ! last_result->_result_content) { 
493                         printf("We're not going to call 'relay' with no result params\n");
494                         return 1;
495                 }
496                 else {
497                         jsonObject* o = jsonNewObject(NULL);
498                         jsonObjectPush(o, last_result->_result_content );
499                         params = o;
500                 }
501         }
502
503
504         if(buffer->n_used > 0 && params == NULL) {
505                 fprintf(stderr, "JSON error detected, not executing\n");
506                 return 1;
507         }
508
509         osrf_app_session* session = osrf_app_client_session_init(server);
510
511         if(!osrf_app_session_connect(session)) {
512                 osrfLogWarning( "Unable to connect to remote service %s\n", server );
513                 return 1;
514         }
515
516         double start = get_timestamp_millis();
517         //int req_id = osrf_app_session_make_request( session, params, method, 1, NULL );
518         int req_id = osrf_app_session_make_req( session, params, method, 1, NULL );
519
520
521         osrf_message* omsg = osrf_app_session_request_recv( session, req_id, 60 );
522
523         if(!omsg) 
524                 printf("\nReceived no data from server\n");
525         
526         
527         signal(SIGPIPE, SIG_IGN);
528
529         FILE* less; 
530         if(!is_from_script) less = popen( "less -EX", "w");
531         else less = stdout;
532
533         if( less == NULL ) { less = stdout; }
534
535         growing_buffer* resp_buffer = buffer_init(4096);
536
537         while(omsg) {
538
539                 if(raw_print) {
540
541                         if(omsg->_result_content) {
542         
543                                 osrf_message_free(last_result);
544                                 last_result = omsg;
545         
546                                 char* content;
547         
548                                 if( pretty_print && omsg->_result_content ) {
549                                         char* j = jsonObjectToJSON(omsg->_result_content);
550                                         //content = json_printer(j); 
551                                         content = jsonFormatString(j);
552                                         free(j);
553                                 } else
554                                         content = jsonObjectGetString(omsg->_result_content);
555         
556                                 printf( "\nReceived Data: %s\n", content ); 
557                                 free(content);
558         
559                         } else {
560
561                                 char code[16];
562                                 memset(code, 0, 16);
563                                 sprintf( code, "%d", omsg->status_code );
564                                 buffer_add( resp_buffer, code );
565
566                                 printf( "\nReceived Exception:\nName: %s\nStatus: %s\nStatus: %s\n", 
567                                                 omsg->status_name, omsg->status_text, code );
568
569                                 fflush(stdout);
570                         }
571
572                 } else {
573
574                         if(omsg->_result_content) {
575         
576                                 osrf_message_free(last_result);
577                                 last_result = omsg;
578         
579                                 char* content;
580         
581                                 if( pretty_print && omsg->_result_content ) {
582                                         char* j = jsonObjectToJSON(omsg->_result_content);
583                                         //content = json_printer(j); 
584                                         content = jsonFormatString(j);
585                                         free(j);
586                                 } else
587                                         content = jsonObjectGetString(omsg->_result_content);
588         
589                                 buffer_add( resp_buffer, "\nReceived Data: " ); 
590                                 buffer_add( resp_buffer, content );
591                                 buffer_add( resp_buffer, "\n" );
592                                 free(content);
593         
594                         } else {
595         
596                                 buffer_add( resp_buffer, "\nReceived Exception:\nName: " );
597                                 buffer_add( resp_buffer, omsg->status_name );
598                                 buffer_add( resp_buffer, "\nStatus: " );
599                                 buffer_add( resp_buffer, omsg->status_text );
600                                 buffer_add( resp_buffer, "\nStatus: " );
601                                 char code[16];
602                                 memset(code, 0, 16);
603                                 sprintf( code, "%d", omsg->status_code );
604                                 buffer_add( resp_buffer, code );
605                         }
606                 }
607
608
609                 omsg = osrf_app_session_request_recv( session, req_id, 5 );
610
611         }
612
613         double end = get_timestamp_millis();
614
615         fprintf( less, resp_buffer->buf );
616         buffer_free( resp_buffer );
617         fprintf( less, "\n------------------------------------\n");
618         if( osrf_app_session_request_complete( session, req_id ))
619                 fprintf(less, "Request Completed Successfully\n");
620
621
622         fprintf(less, "Request Time in seconds: %.6f\n", end - start );
623         fprintf(less, "------------------------------------\n");
624
625         pclose(less); 
626
627         osrf_app_session_request_finish( session, req_id );
628         osrf_app_session_disconnect( session );
629         osrf_app_session_destroy( session );
630
631
632         return 1;
633
634
635 }
636
637 /*
638 int handle_time( char* words[] ) {
639
640         if( ! words[1] ) {
641
642                 char buf[36];
643                 memset(buf,0,36);
644                 get_timestamp(buf);
645                 printf( "%s\n", buf );
646                 return 1;
647         }
648
649         if( words[1] ) {
650                 time_t epoch = (time_t)atoi( words[1] );
651                 char* localtime = strdup( ctime( &epoch ) );
652                 printf( "%s => %s", words[1], localtime );
653                 free(localtime);
654                 return 1;
655         }
656
657         return 0;
658
659 }
660 */
661
662                 
663
664 int router_query_servers( char* router_server ) {
665
666         if( ! router_server || strlen(router_server) == 0 ) 
667                 return 0;
668
669         char rbuf[256];
670         memset(rbuf,0,256);
671         sprintf(rbuf,"router@%s/router", router_server );
672                 
673         transport_message* send = 
674                 message_init( "servers", NULL, NULL, rbuf, NULL );
675         message_set_router_info( send, NULL, NULL, NULL, "query", 0 );
676
677         client_send_message( client, send );
678         message_free( send );
679
680         transport_message* recv = client_recv( client, -1 );
681         if( recv == NULL ) {
682                 fprintf(stderr, "NULL message received from router\n");
683                 return 1;
684         }
685         
686         printf( 
687                         "---------------------------------------------------------------------------------\n"
688                         "Received from 'server' query on %s\n"
689                         "---------------------------------------------------------------------------------\n"
690                         "original reg time | latest reg time | last used time | class | server\n"
691                         "---------------------------------------------------------------------------------\n"
692                         "%s"
693                         "---------------------------------------------------------------------------------\n"
694                         , router_server, recv->body );
695
696         message_free( recv );
697         
698         return 1;
699 }
700                 
701 int print_help() {
702
703         printf(
704                         "---------------------------------------------------------------------------------\n"
705                         "Commands:\n"
706                         "---------------------------------------------------------------------------------\n"
707                         "help                   - Display this message\n"
708                         "!<command> [args] - Forks and runs the given command in the shell\n"
709                         "time                   - Prints the current time\n"                                    
710                         "time <timestamp>       - Formats seconds since epoch into readable format\n"   
711                         "set <variable> <value> - set a srfsh variable (e.g. set pretty_print true )\n"
712                         "print <variable>               - Displays the value of a srfsh variable\n"
713                         "---------------------------------------------------------------------------------\n"
714
715                         "router query servers <server1 [, server2, ...]>\n"
716                         "       - Returns stats on connected services\n"
717                         "\n"
718                         "\n"
719                         "request <service> <method> [ <json formatted string of params> ]\n"
720                         "       - Anything passed in will be wrapped in a json array,\n"
721                         "               so add commas if there is more than one param\n"
722                         "\n"
723                         "\n"
724                         "relay <service> <method>\n"
725                         "       - Performs the requested query using the last received result as the param\n"
726                         "\n"
727                         "\n"
728                         "math_bench <num_batches> [0|1|2]\n"
729                         "       - 0 means don't reconnect, 1 means reconnect after each batch of 4, and\n"
730                         "                2 means reconnect after every request\n"
731                         "\n"
732                         "introspect <service>\n"
733                         "       - prints the API for the service\n"
734                         "\n"
735                         "\n"
736                         "---------------------------------------------------------------------------------\n"
737                         " Commands for Open-ILS\n"
738                         "---------------------------------------------------------------------------------\n"
739                         "login <username> <password>\n"
740                         "       -       Logs into the 'server' and displays the session id\n"
741                         "       - To view the session id later, enter: print login\n"
742                         "---------------------------------------------------------------------------------\n"
743                         "\n"
744                         "\n"
745                         "Note: long output is piped through 'less'.  To search in 'less', type: /<search>\n"
746                         "---------------------------------------------------------------------------------\n"
747                         "\n"
748                         );
749
750         return 1;
751 }
752
753
754
755 char* tabs(int count) {
756         growing_buffer* buf = buffer_init(24);
757         int i;
758         for(i=0;i!=count;i++)
759                 buffer_add(buf, "  ");
760
761         char* final = buffer_data( buf );
762         buffer_free( buf );
763         return final;
764 }
765
766 int handle_math( char* words[] ) {
767         if( words[1] )
768                 return do_math( atoi(words[1]), 0 );
769         return 0;
770 }
771
772
773 int do_math( int count, int style ) {
774
775         osrf_app_session* session = osrf_app_client_session_init(  "opensrf.math" );
776
777         jsonObject* params = json_parse_string("[]");
778         jsonObjectPush(params,jsonNewObject("1"));
779         jsonObjectPush(params,jsonNewObject("2"));
780
781         char* methods[] = { "add", "sub", "mult", "div" };
782         char* answers[] = { "3", "-1", "2", "0.500000" };
783
784         float times[ count * 4 ];
785         memset(times,0,count*4);
786
787         int k;
788         for(k=0;k!=100;k++) {
789                 if(!(k%10)) 
790                         fprintf(stderr,"|");
791                 else
792                         fprintf(stderr,".");
793         }
794
795         fprintf(stderr,"\n\n");
796
797         int running = 0;
798         int i;
799         for(i=0; i!= count; i++) {
800
801                 int j;
802                 for(j=0; j != 4; j++) {
803
804                         ++running;
805
806                         double start = get_timestamp_millis();
807                         int req_id = osrf_app_session_make_req( session, params, methods[j], 1, NULL );
808                         osrf_message* omsg = osrf_app_session_request_recv( session, req_id, 5 );
809                         double end = get_timestamp_millis();
810
811                         times[(4*i) + j] = end - start;
812
813                         if(omsg) {
814         
815                                 if(omsg->_result_content) {
816                                         char* jsn = jsonObjectToJSON(omsg->_result_content);
817                                         if(!strcmp(jsn, answers[j]))
818                                                 fprintf(stderr, "+");
819                                         else
820                                                 fprintf(stderr, "\n![%s] - should be %s\n", jsn, answers[j] );
821                                         free(jsn);
822                                 }
823
824
825                                 osrf_message_free(omsg);
826                 
827                         } else { fprintf( stderr, "\nempty message for tt: %d\n", req_id ); }
828
829                         osrf_app_session_request_finish( session, req_id );
830
831                         if(style == 2)
832                                 osrf_app_session_disconnect( session );
833
834                         if(!(running%100))
835                                 fprintf(stderr,"\n");
836                 }
837
838                 if(style==1)
839                         osrf_app_session_disconnect( session );
840         }
841
842         osrf_app_session_destroy( session );
843         jsonObjectFree(params);
844
845         int c;
846         float total = 0;
847         for(c=0; c!= count*4; c++) 
848                 total += times[c];
849
850         float avg = total / (count*4); 
851         fprintf(stderr, "\n      Average round trip time: %f\n", avg );
852
853         return 1;
854 }