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( const char* server );
60 static int print_help( void );
62 //static int srfsh_client_connect();
63 //static char* tabs(int count);
64 //static void sig_child_handler( int s );
65 //static void sig_int_handler( int s );
67 static int load_history( void );
68 static int handle_math( char* words[] );
69 static int do_math( int count, int style );
70 static int handle_introspect(char* words[]);
71 static int handle_login( char* words[]);
73 static int recv_timeout = 120;
74 static int is_from_script = 0;
75 static FILE* shell_writer = NULL;
76 // static FILE* shell_reader = NULL;
79 int main( int argc, char* argv[] ) {
81 /* --------------------------------------------- */
82 /* see if they have a .srfsh.xml in their home directory */
83 char* home = getenv("HOME");
84 int l = strlen(home) + 36;
87 sprintf(fbuf,"%s/.srfsh.xml",home);
89 if(!access(fbuf, R_OK)) {
90 if( ! osrf_system_bootstrap_client(fbuf, "srfsh") ) {
91 fprintf(stderr,"Unable to bootstrap client for requests\n");
92 osrfLogError( OSRF_LOG_MARK, "Unable to bootstrap client for requests");
97 fprintf(stderr,"No Config file found at %s\n", fbuf );
102 /* for now.. the first arg is used as a script file for processing */
104 if( (f = open(argv[1], O_RDONLY)) == -1 ) {
105 osrfLogError( OSRF_LOG_MARK, "Unable to open file %s for reading, exiting...", argv[1]);
109 if(dup2(f, STDIN_FILENO) == -1) {
110 osrfLogError( OSRF_LOG_MARK, "Unable to duplicate STDIN, exiting...");
118 /* --------------------------------------------- */
122 client = osrf_system_get_transport_client();
124 /* open the shell handle */
125 shell_writer = popen( "bash", "w");
126 //shell_reader = popen( "bash", "r");
128 /* main process loop */
130 while((request=readline(prompt))) {
132 if( !strcasecmp(request, "exit") || !strcasecmp(request,"quit"))
135 char* req_copy = strdup(request);
137 parse_request( req_copy );
138 if( request && strlen(request) > 1 ) {
139 add_history(request);
145 fflush(shell_writer);
150 if(history_file != NULL )
151 write_history(history_file);
155 osrf_system_shutdown();
160 static void sig_child_handler( int s ) {
166 void sig_int_handler( int s ) {
169 signal(SIGINT,sig_int_handler);
173 static int load_history( void ) {
175 char* home = getenv("HOME");
176 int l = strlen(home) + 24;
180 sprintf(fbuf,"%s/.srfsh_history",home);
181 history_file = strdup(fbuf);
183 if(!access(history_file, W_OK | R_OK )) {
184 history_length = 5000;
185 read_history(history_file);
191 static int parse_error( char* words[] ) {
196 growing_buffer * gbuf = buffer_init( 64 );
197 buffer_add( gbuf, *words );
199 buffer_add( gbuf, " " );
200 buffer_add( gbuf, *words );
202 fprintf( stderr, "???: %s\n", gbuf->buf );
210 static int parse_request( char* request ) {
212 if( request == NULL )
215 char * original_request = strdup( request );
219 char* words[COMMAND_BUFSIZE];
220 memset(words,0,COMMAND_BUFSIZE);
223 char* cur_tok = strtok( req, " " );
225 if( cur_tok == NULL )
227 free( original_request );
231 while(cur_tok != NULL) {
232 words[i++] = cur_tok;
233 cur_tok = strtok( NULL, " " );
237 // not sure why (strtok?), but this is necessary
238 memset( words + i, 0, COMMAND_BUFSIZE - i );
240 /* pass off to the top level command */
241 if( !strcmp(words[0],"router") )
242 ret_val = handle_router( words );
245 else if( !strcmp(words[0],"time") )
246 ret_val = handle_time( words );
249 else if (!strcmp(words[0],"request"))
250 ret_val = handle_request( words, 0 );
252 else if (!strcmp(words[0],"relay"))
253 ret_val = handle_request( words, 1 );
255 else if (!strcmp(words[0],"help"))
256 ret_val = print_help();
258 else if (!strcmp(words[0],"set"))
259 ret_val = handle_set(words);
261 else if (!strcmp(words[0],"print"))
262 ret_val = handle_print(words);
264 else if (!strcmp(words[0],"math_bench"))
265 ret_val = handle_math(words);
267 else if (!strcmp(words[0],"introspect"))
268 ret_val = handle_introspect(words);
270 else if (!strcmp(words[0],"login"))
271 ret_val = handle_login(words);
273 else if (words[0][0] == '!') {
274 //ret_val = handle_exec( words, 1 );
275 system( original_request + 1 );
279 free( original_request );
283 return handle_exec( words, 0 );
285 return parse_error( words );
294 static int handle_introspect(char* words[]) {
296 if(words[1] && words[2]) {
297 fprintf(stderr, "--> %s\n", words[1]);
300 sprintf( buf, "request %s opensrf.system.method %s", words[1], words[2] );
301 return parse_request( buf );
306 fprintf(stderr, "--> %s\n", words[1]);
309 sprintf( buf, "request %s opensrf.system.method.all", words[1] );
310 return parse_request( buf );
318 static int handle_login( char* words[]) {
320 if( words[1] && words[2]) {
322 char* username = words[1];
323 char* password = words[2];
324 char* type = words[3];
325 char* orgloc = words[4];
326 char* workstation = words[5];
327 int orgloci = (orgloc) ? atoi(orgloc) : 0;
328 if(!type) type = "opac";
337 "request open-ils.auth open-ils.auth.authenticate.init \"%s\"", username );
341 if(last_result && last_result->_result_content) {
342 jsonObject* r = last_result->_result_content;
343 hash = jsonObjectGetString(r);
347 char* pass_buf = md5sum(password);
350 memset(both_buf,0,256);
351 sprintf(both_buf,"%s%s",hash, pass_buf);
353 char* mess_buf = md5sum(both_buf);
356 sprintf( buf2, "request open-ils.auth open-ils.auth.authenticate.complete "
357 "{ \"username\" : \"%s\", \"password\" : \"%s\", "
358 "\"type\" : \"%s\", \"org\" : %d, \"workstation\": \"%s\"}",
359 username, mess_buf, type, orgloci, workstation );
362 growing_buffer* argbuf = buffer_init(64);
364 "request open-ils.auth open-ils.auth.authenticate.complete "
365 "{ \"username\" : \"%s\", \"password\" : \"%s\"", username, mess_buf );
367 if(type) buffer_fadd( argbuf, ", \"type\" : \"%s\"", type );
368 if(orgloci) buffer_fadd( argbuf, ", \"org\" : %d", orgloci );
369 if(workstation) buffer_fadd( argbuf, ", \"workstation\" : \"%s\"", workstation);
370 buffer_add(argbuf, "}");
375 parse_request( argbuf->buf );
378 jsonObject* x = last_result->_result_content;
381 char* authtoken = jsonObjectGetString(
382 jsonObjectGetKey(jsonObjectGetKey(x,"payload"), "authtoken"));
383 authtime = jsonObjectGetNumber(
384 jsonObjectGetKey(jsonObjectGetKey(x,"payload"), "authtime"));
385 if(authtoken) login_session = strdup(authtoken);
386 else login_session = NULL;
388 else login_session = NULL;
390 printf("Login Session: %s. Session timeout: %f\n", login_session, authtime );
399 static int handle_set( char* words[]) {
402 if( (variable=words[1]) ) {
405 if( (val=words[2]) ) {
407 if(!strcmp(variable,"pretty_print")) {
408 if(!strcmp(val,"true")) {
410 printf("pretty_print = true\n");
413 if(!strcmp(val,"false")) {
415 printf("pretty_print = false\n");
420 if(!strcmp(variable,"raw_print")) {
421 if(!strcmp(val,"true")) {
423 printf("raw_print = true\n");
426 if(!strcmp(val,"false")) {
428 printf("raw_print = false\n");
440 static int handle_print( char* words[]) {
443 if( (variable=words[1]) ) {
444 if(!strcmp(variable,"pretty_print")) {
446 printf("pretty_print = true\n");
449 printf("pretty_print = false\n");
454 if(!strcmp(variable,"login")) {
455 printf("login session = %s\n", login_session );
463 static int handle_router( char* words[] ) {
471 if( !strcmp(words[1],"query") ) {
473 if( words[2] && !strcmp(words[2],"servers") ) {
474 for(i=3; i < COMMAND_BUFSIZE - 3 && words[i]; i++ ) {
475 router_query_servers( words[i] );
487 /* if new shell, spawn a new child and subshell to do the work,
488 otherwise pipe the request to the currently open (piped) shell */
490 static int handle_exec(char* words[], int new_shell) {
492 if(!words[0]) return 0;
494 if( words[0] && words[0][0] == '!') {
495 int len = strlen(words[0]);
497 memset(command,0,len);
499 int i; // chop out the !
500 for( i=1; i!= len; i++) {
501 command[i-1] = words[0][i];
505 words[0] = strdup(command);
509 signal(SIGCHLD, sig_child_handler);
515 signal(SIGCHLD,sig_child_handler);
520 execvp( words[0], words );
527 growing_buffer* b = buffer_init(64);
530 buffer_fadd( b, "%s ", words[i++] );
532 buffer_add( b, "\n");
534 fprintf( shell_writer, b->buf );
537 fflush(shell_writer);
548 static int handle_request( char* words[], int relay ) {
554 char* server = words[1];
555 char* method = words[2];
557 growing_buffer* buffer = NULL;
559 buffer = buffer_init(128);
560 buffer_add(buffer, "[");
561 for(i = 3; words[i] != NULL; i++ ) {
562 /* removes trailing semicolon if user accidentally enters it */
563 if( words[i][strlen(words[i])-1] == ';' )
564 words[i][strlen(words[i])-1] = '\0';
565 buffer_add( buffer, words[i] );
566 buffer_add(buffer, " ");
568 buffer_add(buffer, "]");
571 return send_request( server, method, buffer, relay );
577 int send_request( char* server,
578 char* method, growing_buffer* buffer, int relay ) {
579 if( server == NULL || method == NULL )
582 jsonObject* params = NULL;
584 if( buffer != NULL && buffer->n_used > 0 )
585 params = json_parse_string(buffer->buf);
587 if(!last_result || ! last_result->_result_content) {
588 printf("We're not going to call 'relay' with no result params\n");
592 jsonObject* o = jsonNewObject(NULL);
593 jsonObjectPush(o, last_result->_result_content );
599 if(buffer->n_used > 0 && params == NULL) {
600 fprintf(stderr, "JSON error detected, not executing\n");
604 osrf_app_session* session = osrf_app_client_session_init(server);
606 if(!osrf_app_session_connect(session)) {
607 osrfLogWarning( OSRF_LOG_MARK, "Unable to connect to remote service %s\n", server );
611 double start = get_timestamp_millis();
612 //int req_id = osrf_app_session_make_request( session, params, method, 1, NULL );
613 int req_id = osrf_app_session_make_req( session, params, method, 1, NULL );
616 osrf_message* omsg = osrf_app_session_request_recv( session, req_id, recv_timeout );
619 printf("\nReceived no data from server\n");
622 signal(SIGPIPE, SIG_IGN);
625 if(!is_from_script) less = popen( "less -EX", "w");
628 if( less == NULL ) { less = stdout; }
630 growing_buffer* resp_buffer = buffer_init(4096);
636 if(omsg->_result_content) {
638 osrf_message_free(last_result);
643 if( pretty_print && omsg->_result_content ) {
644 char* j = jsonObjectToJSON(omsg->_result_content);
645 //content = json_printer(j);
646 content = jsonFormatString(j);
649 content = jsonObjectGetString(omsg->_result_content);
651 printf( "\nReceived Data: %s\n", content );
658 sprintf( code, "%d", omsg->status_code );
659 buffer_add( resp_buffer, code );
661 printf( "\nReceived Exception:\nName: %s\nStatus: %s\nStatus: %s\n",
662 omsg->status_name, omsg->status_text, code );
669 if(omsg->_result_content) {
671 osrf_message_free(last_result);
676 if( pretty_print && omsg->_result_content ) {
677 char* j = jsonObjectToJSON(omsg->_result_content);
678 //content = json_printer(j);
679 content = jsonFormatString(j);
682 content = jsonObjectGetString(omsg->_result_content);
684 buffer_add( resp_buffer, "\nReceived Data: " );
685 buffer_add( resp_buffer, content );
686 buffer_add( resp_buffer, "\n" );
691 buffer_add( resp_buffer, "\nReceived Exception:\nName: " );
692 buffer_add( resp_buffer, omsg->status_name );
693 buffer_add( resp_buffer, "\nStatus: " );
694 buffer_add( resp_buffer, omsg->status_text );
695 buffer_add( resp_buffer, "\nStatus: " );
698 sprintf( code, "%d", omsg->status_code );
699 buffer_add( resp_buffer, code );
704 omsg = osrf_app_session_request_recv( session, req_id, recv_timeout );
708 double end = get_timestamp_millis();
710 fprintf( less, resp_buffer->buf );
711 buffer_free( resp_buffer );
712 fprintf( less, "\n------------------------------------\n");
713 if( osrf_app_session_request_complete( session, req_id ))
714 fprintf(less, "Request Completed Successfully\n");
717 fprintf(less, "Request Time in seconds: %.6f\n", end - start );
718 fprintf(less, "------------------------------------\n");
722 osrf_app_session_request_finish( session, req_id );
723 osrf_app_session_disconnect( session );
724 osrf_app_session_destroy( session );
733 static int handle_time( char* words[] ) {
740 printf( "%s\n", buf );
745 time_t epoch = (time_t)atoi( words[1] );
746 char* localtime = strdup( ctime( &epoch ) );
747 printf( "%s => %s", words[1], localtime );
759 static int router_query_servers( const char* router_server ) {
761 if( ! router_server || strlen(router_server) == 0 )
766 sprintf(rbuf,"router@%s/router", router_server );
768 transport_message* send =
769 message_init( "servers", NULL, NULL, rbuf, NULL );
770 message_set_router_info( send, NULL, NULL, NULL, "query", 0 );
772 client_send_message( client, send );
773 message_free( send );
775 transport_message* recv = client_recv( client, -1 );
777 fprintf(stderr, "NULL message received from router\n");
782 "---------------------------------------------------------------------------------\n"
783 "Received from 'server' query on %s\n"
784 "---------------------------------------------------------------------------------\n"
785 "original reg time | latest reg time | last used time | class | server\n"
786 "---------------------------------------------------------------------------------\n"
788 "---------------------------------------------------------------------------------\n"
789 , router_server, recv->body );
791 message_free( recv );
796 static int print_help( void ) {
799 "---------------------------------------------------------------------------------\n"
801 "---------------------------------------------------------------------------------\n"
802 "help - Display this message\n"
803 "!<command> [args] - Forks and runs the given command in the shell\n"
805 "time - Prints the current time\n"
806 "time <timestamp> - Formats seconds since epoch into readable format\n"
808 "set <variable> <value> - set a srfsh variable (e.g. set pretty_print true )\n"
809 "print <variable> - Displays the value of a srfsh variable\n"
810 "---------------------------------------------------------------------------------\n"
812 "router query servers <server1 [, server2, ...]>\n"
813 " - Returns stats on connected services\n"
816 "request <service> <method> [ <json formatted string of params> ]\n"
817 " - Anything passed in will be wrapped in a json array,\n"
818 " so add commas if there is more than one param\n"
821 "relay <service> <method>\n"
822 " - Performs the requested query using the last received result as the param\n"
825 "math_bench <num_batches> [0|1|2]\n"
826 " - 0 means don't reconnect, 1 means reconnect after each batch of 4, and\n"
827 " 2 means reconnect after every request\n"
829 "introspect <service>\n"
830 " - prints the API for the service\n"
833 "---------------------------------------------------------------------------------\n"
834 " Commands for Open-ILS\n"
835 "---------------------------------------------------------------------------------\n"
836 "login <username> <password>\n"
837 " - Logs into the 'server' and displays the session id\n"
838 " - To view the session id later, enter: print login\n"
839 "---------------------------------------------------------------------------------\n"
842 "Note: long output is piped through 'less'. To search in 'less', type: /<search>\n"
843 "---------------------------------------------------------------------------------\n"
852 static char* tabs(int count) {
853 growing_buffer* buf = buffer_init(24);
855 for(i=0;i!=count;i++)
856 buffer_add(buf, " ");
858 char* final = buffer_data( buf );
865 static int handle_math( char* words[] ) {
867 return do_math( atoi(words[1]), 0 );
872 static int do_math( int count, int style ) {
874 osrf_app_session* session = osrf_app_client_session_init( "opensrf.math" );
875 osrf_app_session_connect(session);
877 jsonObject* params = json_parse_string("[]");
878 jsonObjectPush(params,jsonNewObject("1"));
879 jsonObjectPush(params,jsonNewObject("2"));
881 char* methods[] = { "add", "sub", "mult", "div" };
882 char* answers[] = { "3", "-1", "2", "0.500000" };
884 float times[ count * 4 ];
885 memset(times,0,count*4);
888 for(k=0;k!=100;k++) {
895 fprintf(stderr,"\n\n");
899 for(i=0; i!= count; i++) {
902 for(j=0; j != 4; j++) {
906 double start = get_timestamp_millis();
907 int req_id = osrf_app_session_make_req( session, params, methods[j], 1, NULL );
908 osrf_message* omsg = osrf_app_session_request_recv( session, req_id, 5 );
909 double end = get_timestamp_millis();
911 times[(4*i) + j] = end - start;
915 if(omsg->_result_content) {
916 char* jsn = jsonObjectToJSON(omsg->_result_content);
917 if(!strcmp(jsn, answers[j]))
918 fprintf(stderr, "+");
920 fprintf(stderr, "\n![%s] - should be %s\n", jsn, answers[j] );
925 osrf_message_free(omsg);
927 } else { fprintf( stderr, "\nempty message for tt: %d\n", req_id ); }
929 osrf_app_session_request_finish( session, req_id );
932 osrf_app_session_disconnect( session );
935 fprintf(stderr,"\n");
939 osrf_app_session_disconnect( session );
942 osrf_app_session_destroy( session );
943 jsonObjectFree(params);
947 for(c=0; c!= count*4; c++)
950 float avg = total / (count*4);
951 fprintf(stderr, "\n Average round trip time: %f\n", avg );