1 #include <opensrf/transport_client.h>
2 #include <opensrf/osrf_message.h>
3 #include <opensrf/osrf_app_session.h>
9 #include <opensrf/utils.h>
10 #include <opensrf/log.h>
15 #include <readline/readline.h>
16 #include <readline/history.h>
18 #define SRFSH_PORT 5222
19 #define COMMAND_BUFSIZE 4096
23 static const char* prompt = "srfsh# ";
25 static char* history_file = NULL;
27 static int child_dead = 0;
29 static char* login_session = NULL;
31 /* true if we're pretty printing json results */
32 static int pretty_print = 1;
33 /* true if we're bypassing 'less' */
34 static int raw_print = 0;
36 /* our jabber connection */
37 static transport_client* client = NULL;
39 /* the last result we received */
40 static osrf_message* last_result = NULL;
43 static int parse_request( char* request );
45 /* handles router requests */
46 static int handle_router( char* words[] );
48 /* utility method for print time data */
49 /* static int handle_time( char* words[] ); */
51 /* handles app level requests */
52 static int handle_request( char* words[], int relay );
53 static int handle_exec(char* words[], int new_shell);
54 static int handle_set( char* words[]);
55 static int handle_print( char* words[]);
56 static int send_request( char* server,
57 char* method, growing_buffer* buffer, int relay );
58 static int parse_error( char* words[] );
59 static int router_query_servers( char* server );
60 //static int srfsh_client_connect();
61 static int print_help();
62 //static char* tabs(int count);
63 static void sig_child_handler( int s );
64 //static void sig_int_handler( int s );
66 static int load_history();
67 static int handle_math( char* words[] );
68 static int do_math( int count, int style );
69 static int handle_introspect(char* words[]);
70 static int handle_login( char* words[]);
72 static int recv_timeout = 120;
73 static int is_from_script = 0;
74 static FILE* shell_writer = NULL;
75 // static FILE* shell_reader = NULL;
78 int main( int argc, char* argv[] ) {
80 /* --------------------------------------------- */
81 /* see if they have a .srfsh.xml in their home directory */
82 char* home = getenv("HOME");
83 int l = strlen(home) + 36;
86 sprintf(fbuf,"%s/.srfsh.xml",home);
88 if(!access(fbuf, R_OK)) {
89 if( ! osrf_system_bootstrap_client(fbuf, "srfsh") ) {
90 fprintf(stderr,"Unable to bootstrap client for requests\n");
91 osrfLogError( OSRF_LOG_MARK, "Unable to bootstrap client for requests");
96 fprintf(stderr,"No Config file found at %s\n", fbuf );
101 /* for now.. the first arg is used as a script file for processing */
103 if( (f = open(argv[1], O_RDONLY)) == -1 ) {
104 osrfLogError( OSRF_LOG_MARK, "Unable to open file %s for reading, exiting...", argv[1]);
108 if(dup2(f, STDIN_FILENO) == -1) {
109 osrfLogError( OSRF_LOG_MARK, "Unable to duplicate STDIN, exiting...");
117 /* --------------------------------------------- */
121 client = osrf_system_get_transport_client();
123 /* open the shell handle */
124 shell_writer = popen( "bash", "w");
125 //shell_reader = popen( "bash", "r");
127 /* main process loop */
129 while((request=readline(prompt))) {
131 if( !strcasecmp(request, "exit") || !strcasecmp(request,"quit"))
134 char* req_copy = strdup(request);
136 parse_request( req_copy );
137 if( request && strlen(request) > 1 ) {
138 add_history(request);
144 fflush(shell_writer);
149 if(history_file != NULL )
150 write_history(history_file);
154 osrf_system_shutdown();
158 static void sig_child_handler( int s ) {
163 void sig_int_handler( int s ) {
166 signal(SIGINT,sig_int_handler);
170 static int load_history() {
172 char* home = getenv("HOME");
173 int l = strlen(home) + 24;
177 sprintf(fbuf,"%s/.srfsh_history",home);
178 history_file = strdup(fbuf);
180 if(!access(history_file, W_OK | R_OK )) {
181 history_length = 5000;
182 read_history(history_file);
188 static int parse_error( char* words[] ) {
197 memset(buffer, 0, 256);
198 while( (current=words[i++]) ) {
199 strcat(buffer, current);
202 if( ! buffer || strlen(buffer) < 1 )
205 fprintf( stderr, "???: %s\n", buffer );
211 static int parse_request( char* request ) {
213 if( request == NULL )
218 char* words[COMMAND_BUFSIZE];
219 memset(words,0,COMMAND_BUFSIZE);
222 char* cur_tok = strtok( req, " " );
224 if( cur_tok == NULL )
227 while(cur_tok != NULL) {
228 words[i++] = cur_tok;
229 cur_tok = strtok( NULL, " " );
233 // not sure why (strtok?), but this is necessary
234 memset( words + i, 0, COMMAND_BUFSIZE - i );
236 /* pass off to the top level command */
237 if( !strcmp(words[0],"router") )
238 ret_val = handle_router( words );
241 else if( !strcmp(words[0],"time") )
242 ret_val = handle_time( words );
245 else if (!strcmp(words[0],"request"))
246 ret_val = handle_request( words, 0 );
248 else if (!strcmp(words[0],"relay"))
249 ret_val = handle_request( words, 1 );
251 else if (!strcmp(words[0],"help"))
252 ret_val = print_help();
254 else if (!strcmp(words[0],"set"))
255 ret_val = handle_set(words);
257 else if (!strcmp(words[0],"print"))
258 ret_val = handle_print(words);
260 else if (!strcmp(words[0],"math_bench"))
261 ret_val = handle_math(words);
263 else if (!strcmp(words[0],"introspect"))
264 ret_val = handle_introspect(words);
266 else if (!strcmp(words[0],"login"))
267 ret_val = handle_login(words);
269 else if (words[0][0] == '!')
270 ret_val = handle_exec( words, 1 );
274 return handle_exec( words, 0 );
276 return parse_error( words );
285 static int handle_introspect(char* words[]) {
287 if(words[1] && words[2]) {
288 fprintf(stderr, "--> %s\n", words[1]);
291 sprintf( buf, "request %s opensrf.system.method %s", words[1], words[2] );
292 return parse_request( buf );
297 fprintf(stderr, "--> %s\n", words[1]);
300 sprintf( buf, "request %s opensrf.system.method.all", words[1] );
301 return parse_request( buf );
309 static int handle_login( char* words[]) {
311 if( words[1] && words[2]) {
313 char* username = words[1];
314 char* password = words[2];
315 char* type = words[3];
316 char* orgloc = words[4];
317 char* workstation = words[5];
318 int orgloci = (orgloc) ? atoi(orgloc) : 0;
319 if(!type) type = "opac";
328 "request open-ils.auth open-ils.auth.authenticate.init \"%s\"", username );
332 if(last_result && last_result->_result_content) {
333 jsonObject* r = last_result->_result_content;
334 hash = jsonObjectGetString(r);
338 char* pass_buf = md5sum(password);
341 memset(both_buf,0,256);
342 sprintf(both_buf,"%s%s",hash, pass_buf);
344 char* mess_buf = md5sum(both_buf);
347 sprintf( buf2, "request open-ils.auth open-ils.auth.authenticate.complete "
348 "{ \"username\" : \"%s\", \"password\" : \"%s\", "
349 "\"type\" : \"%s\", \"org\" : %d, \"workstation\": \"%s\"}",
350 username, mess_buf, type, orgloci, workstation );
353 growing_buffer* argbuf = buffer_init(64);
355 "request open-ils.auth open-ils.auth.authenticate.complete "
356 "{ \"username\" : \"%s\", \"password\" : \"%s\"", username, mess_buf );
358 if(type) buffer_fadd( argbuf, ", \"type\" : \"%s\"", type );
359 if(orgloci) buffer_fadd( argbuf, ", \"org\" : %d", orgloci );
360 if(workstation) buffer_fadd( argbuf, ", \"workstation\" : \"%s\"", workstation);
361 buffer_add(argbuf, "}");
366 parse_request( argbuf->buf );
369 jsonObject* x = last_result->_result_content;
372 char* authtoken = jsonObjectGetString(
373 jsonObjectGetKey(jsonObjectGetKey(x,"payload"), "authtoken"));
374 authtime = jsonObjectGetNumber(
375 jsonObjectGetKey(jsonObjectGetKey(x,"payload"), "authtime"));
376 if(authtoken) login_session = strdup(authtoken);
377 else login_session = NULL;
379 else login_session = NULL;
381 printf("Login Session: %s. Session timeout: %f\n", login_session, authtime );
390 static int handle_set( char* words[]) {
393 if( (variable=words[1]) ) {
396 if( (val=words[2]) ) {
398 if(!strcmp(variable,"pretty_print")) {
399 if(!strcmp(val,"true")) {
401 printf("pretty_print = true\n");
404 if(!strcmp(val,"false")) {
406 printf("pretty_print = false\n");
411 if(!strcmp(variable,"raw_print")) {
412 if(!strcmp(val,"true")) {
414 printf("raw_print = true\n");
417 if(!strcmp(val,"false")) {
419 printf("raw_print = false\n");
431 static int handle_print( char* words[]) {
434 if( (variable=words[1]) ) {
435 if(!strcmp(variable,"pretty_print")) {
437 printf("pretty_print = true\n");
440 printf("pretty_print = false\n");
445 if(!strcmp(variable,"login")) {
446 printf("login session = %s\n", login_session );
454 static int handle_router( char* words[] ) {
462 if( !strcmp(words[1],"query") ) {
464 if( words[2] && !strcmp(words[2],"servers") ) {
465 for(i=3; i < COMMAND_BUFSIZE - 3 && words[i]; i++ ) {
466 router_query_servers( words[i] );
478 /* if new shell, spawn a new child and subshell to do the work,
479 otherwise pipe the request to the currently open (piped) shell */
480 static int handle_exec(char* words[], int new_shell) {
482 if(!words[0]) return 0;
484 if( words[0] && words[0][0] == '!') {
485 int len = strlen(words[0]);
487 memset(command,0,len);
489 int i; /* chop out the ! */
490 for( i=1; i!= len; i++) {
491 command[i-1] = words[0][i];
495 words[0] = strdup(command);
499 signal(SIGCHLD, sig_child_handler);
505 signal(SIGCHLD,sig_child_handler);
510 execvp( words[0], words );
517 growing_buffer* b = buffer_init(64);
520 buffer_fadd( b, "%s ", words[i++] );
522 buffer_add( b, "\n");
525 //int reader = dup2(STDOUT_FILENO, reader);
526 //int reader = dup(STDOUT_FILENO);
527 //close(STDOUT_FILENO);
529 fprintf( shell_writer, b->buf );
532 fflush(shell_writer);
538 read( reader, c, 4095 );
539 fprintf(stderr, "read %s", c);
540 dup2(reader, STDOUT_FILENO);
550 static int handle_request( char* words[], int relay ) {
556 char* server = words[1];
557 char* method = words[2];
559 growing_buffer* buffer = NULL;
561 buffer = buffer_init(128);
562 buffer_add(buffer, "[");
563 for(i = 3; words[i] != NULL; i++ ) {
564 /* removes trailing semicolon if user accidentally enters it */
565 if( words[i][strlen(words[i])-1] == ';' )
566 words[i][strlen(words[i])-1] = '\0';
567 buffer_add( buffer, words[i] );
568 buffer_add(buffer, " ");
570 buffer_add(buffer, "]");
573 return send_request( server, method, buffer, relay );
579 int send_request( char* server,
580 char* method, growing_buffer* buffer, int relay ) {
581 if( server == NULL || method == NULL )
584 jsonObject* params = NULL;
586 if( buffer != NULL && buffer->n_used > 0 )
587 params = json_parse_string(buffer->buf);
589 if(!last_result || ! last_result->_result_content) {
590 printf("We're not going to call 'relay' with no result params\n");
594 jsonObject* o = jsonNewObject(NULL);
595 jsonObjectPush(o, last_result->_result_content );
601 if(buffer->n_used > 0 && params == NULL) {
602 fprintf(stderr, "JSON error detected, not executing\n");
606 osrf_app_session* session = osrf_app_client_session_init(server);
608 if(!osrf_app_session_connect(session)) {
609 osrfLogWarning( OSRF_LOG_MARK, "Unable to connect to remote service %s\n", server );
613 double start = get_timestamp_millis();
614 //int req_id = osrf_app_session_make_request( session, params, method, 1, NULL );
615 int req_id = osrf_app_session_make_req( session, params, method, 1, NULL );
618 osrf_message* omsg = osrf_app_session_request_recv( session, req_id, recv_timeout );
621 printf("\nReceived no data from server\n");
624 signal(SIGPIPE, SIG_IGN);
627 if(!is_from_script) less = popen( "less -EX", "w");
630 if( less == NULL ) { less = stdout; }
632 growing_buffer* resp_buffer = buffer_init(4096);
638 if(omsg->_result_content) {
640 osrf_message_free(last_result);
645 if( pretty_print && omsg->_result_content ) {
646 char* j = jsonObjectToJSON(omsg->_result_content);
647 //content = json_printer(j);
648 content = jsonFormatString(j);
651 content = jsonObjectGetString(omsg->_result_content);
653 printf( "\nReceived Data: %s\n", content );
660 sprintf( code, "%d", omsg->status_code );
661 buffer_add( resp_buffer, code );
663 printf( "\nReceived Exception:\nName: %s\nStatus: %s\nStatus: %s\n",
664 omsg->status_name, omsg->status_text, code );
671 if(omsg->_result_content) {
673 osrf_message_free(last_result);
678 if( pretty_print && omsg->_result_content ) {
679 char* j = jsonObjectToJSON(omsg->_result_content);
680 //content = json_printer(j);
681 content = jsonFormatString(j);
684 content = jsonObjectGetString(omsg->_result_content);
686 buffer_add( resp_buffer, "\nReceived Data: " );
687 buffer_add( resp_buffer, content );
688 buffer_add( resp_buffer, "\n" );
693 buffer_add( resp_buffer, "\nReceived Exception:\nName: " );
694 buffer_add( resp_buffer, omsg->status_name );
695 buffer_add( resp_buffer, "\nStatus: " );
696 buffer_add( resp_buffer, omsg->status_text );
697 buffer_add( resp_buffer, "\nStatus: " );
700 sprintf( code, "%d", omsg->status_code );
701 buffer_add( resp_buffer, code );
706 omsg = osrf_app_session_request_recv( session, req_id, recv_timeout );
710 double end = get_timestamp_millis();
712 fprintf( less, resp_buffer->buf );
713 buffer_free( resp_buffer );
714 fprintf( less, "\n------------------------------------\n");
715 if( osrf_app_session_request_complete( session, req_id ))
716 fprintf(less, "Request Completed Successfully\n");
719 fprintf(less, "Request Time in seconds: %.6f\n", end - start );
720 fprintf(less, "------------------------------------\n");
724 osrf_app_session_request_finish( session, req_id );
725 osrf_app_session_disconnect( session );
726 osrf_app_session_destroy( session );
735 static int handle_time( char* words[] ) {
742 printf( "%s\n", buf );
747 time_t epoch = (time_t)atoi( words[1] );
748 char* localtime = strdup( ctime( &epoch ) );
749 printf( "%s => %s", words[1], localtime );
761 static int router_query_servers( char* router_server ) {
763 if( ! router_server || strlen(router_server) == 0 )
768 sprintf(rbuf,"router@%s/router", router_server );
770 transport_message* send =
771 message_init( "servers", NULL, NULL, rbuf, NULL );
772 message_set_router_info( send, NULL, NULL, NULL, "query", 0 );
774 client_send_message( client, send );
775 message_free( send );
777 transport_message* recv = client_recv( client, -1 );
779 fprintf(stderr, "NULL message received from router\n");
784 "---------------------------------------------------------------------------------\n"
785 "Received from 'server' query on %s\n"
786 "---------------------------------------------------------------------------------\n"
787 "original reg time | latest reg time | last used time | class | server\n"
788 "---------------------------------------------------------------------------------\n"
790 "---------------------------------------------------------------------------------\n"
791 , router_server, recv->body );
793 message_free( recv );
798 static int print_help() {
801 "---------------------------------------------------------------------------------\n"
803 "---------------------------------------------------------------------------------\n"
804 "help - Display this message\n"
805 "!<command> [args] - Forks and runs the given command in the shell\n"
807 "time - Prints the current time\n"
808 "time <timestamp> - Formats seconds since epoch into readable format\n"
810 "set <variable> <value> - set a srfsh variable (e.g. set pretty_print true )\n"
811 "print <variable> - Displays the value of a srfsh variable\n"
812 "---------------------------------------------------------------------------------\n"
814 "router query servers <server1 [, server2, ...]>\n"
815 " - Returns stats on connected services\n"
818 "request <service> <method> [ <json formatted string of params> ]\n"
819 " - Anything passed in will be wrapped in a json array,\n"
820 " so add commas if there is more than one param\n"
823 "relay <service> <method>\n"
824 " - Performs the requested query using the last received result as the param\n"
827 "math_bench <num_batches> [0|1|2]\n"
828 " - 0 means don't reconnect, 1 means reconnect after each batch of 4, and\n"
829 " 2 means reconnect after every request\n"
831 "introspect <service>\n"
832 " - prints the API for the service\n"
835 "---------------------------------------------------------------------------------\n"
836 " Commands for Open-ILS\n"
837 "---------------------------------------------------------------------------------\n"
838 "login <username> <password>\n"
839 " - Logs into the 'server' and displays the session id\n"
840 " - To view the session id later, enter: print login\n"
841 "---------------------------------------------------------------------------------\n"
844 "Note: long output is piped through 'less'. To search in 'less', type: /<search>\n"
845 "---------------------------------------------------------------------------------\n"
854 static char* tabs(int count) {
855 growing_buffer* buf = buffer_init(24);
857 for(i=0;i!=count;i++)
858 buffer_add(buf, " ");
860 char* final = buffer_data( buf );
867 static int handle_math( char* words[] ) {
869 return do_math( atoi(words[1]), 0 );
874 static int do_math( int count, int style ) {
876 osrf_app_session* session = osrf_app_client_session_init( "opensrf.math" );
877 osrf_app_session_connect(session);
879 jsonObject* params = json_parse_string("[]");
880 jsonObjectPush(params,jsonNewObject("1"));
881 jsonObjectPush(params,jsonNewObject("2"));
883 char* methods[] = { "add", "sub", "mult", "div" };
884 char* answers[] = { "3", "-1", "2", "0.500000" };
886 float times[ count * 4 ];
887 memset(times,0,count*4);
890 for(k=0;k!=100;k++) {
897 fprintf(stderr,"\n\n");
901 for(i=0; i!= count; i++) {
904 for(j=0; j != 4; j++) {
908 double start = get_timestamp_millis();
909 int req_id = osrf_app_session_make_req( session, params, methods[j], 1, NULL );
910 osrf_message* omsg = osrf_app_session_request_recv( session, req_id, 5 );
911 double end = get_timestamp_millis();
913 times[(4*i) + j] = end - start;
917 if(omsg->_result_content) {
918 char* jsn = jsonObjectToJSON(omsg->_result_content);
919 if(!strcmp(jsn, answers[j]))
920 fprintf(stderr, "+");
922 fprintf(stderr, "\n![%s] - should be %s\n", jsn, answers[j] );
927 osrf_message_free(omsg);
929 } else { fprintf( stderr, "\nempty message for tt: %d\n", req_id ); }
931 osrf_app_session_request_finish( session, req_id );
934 osrf_app_session_disconnect( session );
937 fprintf(stderr,"\n");
941 osrf_app_session_disconnect( session );
944 osrf_app_session_destroy( session );
945 jsonObjectFree(params);
949 for(c=0; c!= count*4; c++)
952 float avg = total / (count*4);
953 fprintf(stderr, "\n Average round trip time: %f\n", avg );