1 #include <opensrf/transport_client.h>
2 #include <opensrf/osrf_message.h>
3 #include <opensrf/osrf_app_session.h>
10 #include <opensrf/utils.h>
11 #include <opensrf/log.h>
16 #include <readline/readline.h>
17 #include <readline/history.h>
19 #define SRFSH_PORT 5222
20 #define COMMAND_BUFSIZE 4096
24 static const char* prompt = "srfsh# ";
26 static char* history_file = NULL;
28 //static int child_dead = 0;
30 static char* login_session = NULL;
32 /* true if we're pretty printing json results */
33 static int pretty_print = 1;
34 /* true if we're bypassing 'less' */
35 static int raw_print = 0;
37 /* our jabber connection */
38 static transport_client* client = NULL;
40 /* the last result we received */
41 static osrf_message* last_result = NULL;
44 static int parse_request( char* request );
46 /* handles router requests */
47 static int handle_router( char* words[] );
49 /* utility method for print time data */
50 /* static int handle_time( char* words[] ); */
52 /* handles app level requests */
53 static int handle_request( char* words[], int relay );
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;
76 int main( int argc, char* argv[] ) {
78 /* --------------------------------------------- */
79 /* see if they have a .srfsh.xml in their home directory */
80 char* home = getenv("HOME");
81 int l = strlen(home) + 36;
84 sprintf(fbuf,"%s/.srfsh.xml",home);
86 if(!access(fbuf, R_OK)) {
87 if( ! osrf_system_bootstrap_client(fbuf, "srfsh") ) {
88 fprintf(stderr,"Unable to bootstrap client for requests\n");
89 osrfLogError( OSRF_LOG_MARK, "Unable to bootstrap client for requests");
94 fprintf(stderr,"No Config file found at %s\n", fbuf );
99 /* for now.. the first arg is used as a script file for processing */
101 if( (f = open(argv[1], O_RDONLY)) == -1 ) {
102 osrfLogError( OSRF_LOG_MARK, "Unable to open file %s for reading, exiting...", argv[1]);
106 if(dup2(f, STDIN_FILENO) == -1) {
107 osrfLogError( OSRF_LOG_MARK, "Unable to duplicate STDIN, exiting...");
115 /* --------------------------------------------- */
119 client = osrf_system_get_transport_client();
121 /* main process loop */
122 int newline_needed = 1; /* used as boolean */
124 while((request=readline(prompt))) {
126 // Find first non-whitespace character
128 char * cmd = request;
129 while( isspace( (unsigned char) *cmd ) )
132 // ignore comments and empty lines
134 if( '\0' == *cmd || '#' == *cmd )
137 // Remove trailing whitespace. We know at this point that
138 // there is at least one non-whitespace character somewhere,
139 // or we would have already skipped this line. Hence we
140 // needn't check to make sure that we don't back up past
144 // The curly braces limit the scope of the end variable
146 char * end = cmd + strlen(cmd) - 1;
147 while( isspace( (unsigned char) *end ) )
152 if( !strcasecmp(cmd, "exit") || !strcasecmp(cmd, "quit"))
158 char* req_copy = strdup(cmd);
160 parse_request( req_copy );
161 if( request && *cmd ) {
162 add_history(request);
172 if( newline_needed ) {
174 // We left the readline loop after seeing an EOF, not after
175 // seeing "quit" or "exit". So we issue a newline in order
176 // to avoid leaving a dangling prompt.
181 if(history_file != NULL )
182 write_history(history_file);
186 osrf_system_shutdown();
191 static void sig_child_handler( int s ) {
197 void sig_int_handler( int s ) {
200 signal(SIGINT,sig_int_handler);
204 static int load_history( void ) {
206 char* home = getenv("HOME");
207 int l = strlen(home) + 24;
211 sprintf(fbuf,"%s/.srfsh_history",home);
212 history_file = strdup(fbuf);
214 if(!access(history_file, W_OK | R_OK )) {
215 history_length = 5000;
216 read_history(history_file);
222 static int parse_error( char* words[] ) {
227 growing_buffer * gbuf = buffer_init( 64 );
228 buffer_add( gbuf, *words );
230 buffer_add( gbuf, " " );
231 buffer_add( gbuf, *words );
233 fprintf( stderr, "???: %s\n", gbuf->buf );
241 static int parse_request( char* request ) {
243 if( request == NULL )
246 char* original_request = strdup( request );
247 char* words[COMMAND_BUFSIZE];
254 char* cur_tok = strtok( req, " " );
256 if( cur_tok == NULL )
258 free( original_request );
262 /* Load an array with pointers to */
263 /* the tokens as defined by strtok() */
265 while(cur_tok != NULL) {
266 if( i < COMMAND_BUFSIZE - 1 ) {
267 words[i++] = cur_tok;
268 cur_tok = strtok( NULL, " " );
270 fprintf( stderr, "Too many tokens in command\n" );
271 free( original_request );
278 /* pass off to the top level command */
279 if( !strcmp(words[0],"router") )
280 ret_val = handle_router( words );
283 else if( !strcmp(words[0],"time") )
284 ret_val = handle_time( words );
287 else if (!strcmp(words[0],"request"))
288 ret_val = handle_request( words, 0 );
290 else if (!strcmp(words[0],"relay"))
291 ret_val = handle_request( words, 1 );
293 else if (!strcmp(words[0],"help"))
294 ret_val = print_help();
296 else if (!strcmp(words[0],"set"))
297 ret_val = handle_set(words);
299 else if (!strcmp(words[0],"print"))
300 ret_val = handle_print(words);
302 else if (!strcmp(words[0],"math_bench"))
303 ret_val = handle_math(words);
305 else if (!strcmp(words[0],"introspect"))
306 ret_val = handle_introspect(words);
308 else if (!strcmp(words[0],"login"))
309 ret_val = handle_login(words);
311 else if (words[0][0] == '!') {
312 system( original_request + 1 );
316 free( original_request );
319 return parse_error( words );
325 static int handle_introspect(char* words[]) {
327 if(words[1] && words[2]) {
328 fprintf(stderr, "--> %s\n", words[1]);
331 sprintf( buf, "request %s opensrf.system.method %s", words[1], words[2] );
332 return parse_request( buf );
337 fprintf(stderr, "--> %s\n", words[1]);
340 sprintf( buf, "request %s opensrf.system.method.all", words[1] );
341 return parse_request( buf );
349 static int handle_login( char* words[]) {
351 if( words[1] && words[2]) {
353 char* username = words[1];
354 char* password = words[2];
355 char* type = words[3];
356 char* orgloc = words[4];
357 char* workstation = words[5];
358 int orgloci = (orgloc) ? atoi(orgloc) : 0;
359 if(!type) type = "opac";
368 "request open-ils.auth open-ils.auth.authenticate.init \"%s\"", username );
372 if(last_result && last_result->_result_content) {
373 jsonObject* r = last_result->_result_content;
374 hash = jsonObjectGetString(r);
378 char* pass_buf = md5sum(password);
381 memset(both_buf,0,256);
382 sprintf(both_buf,"%s%s",hash, pass_buf);
384 char* mess_buf = md5sum(both_buf);
387 sprintf( buf2, "request open-ils.auth open-ils.auth.authenticate.complete "
388 "{ \"username\" : \"%s\", \"password\" : \"%s\", "
389 "\"type\" : \"%s\", \"org\" : %d, \"workstation\": \"%s\"}",
390 username, mess_buf, type, orgloci, workstation );
393 growing_buffer* argbuf = buffer_init(64);
395 "request open-ils.auth open-ils.auth.authenticate.complete "
396 "{ \"username\" : \"%s\", \"password\" : \"%s\"", username, mess_buf );
398 if(type) buffer_fadd( argbuf, ", \"type\" : \"%s\"", type );
399 if(orgloci) buffer_fadd( argbuf, ", \"org\" : %d", orgloci );
400 if(workstation) buffer_fadd( argbuf, ", \"workstation\" : \"%s\"", workstation);
401 buffer_add(argbuf, "}");
406 parse_request( argbuf->buf );
409 jsonObject* x = last_result->_result_content;
412 char* authtoken = jsonObjectGetString(
413 jsonObjectGetKey(jsonObjectGetKey(x,"payload"), "authtoken"));
414 authtime = jsonObjectGetNumber(
415 jsonObjectGetKey(jsonObjectGetKey(x,"payload"), "authtime"));
416 if(authtoken) login_session = strdup(authtoken);
417 else login_session = NULL;
419 else login_session = NULL;
421 printf("Login Session: %s. Session timeout: %f\n", login_session, authtime );
430 static int handle_set( char* words[]) {
433 if( (variable=words[1]) ) {
436 if( (val=words[2]) ) {
438 if(!strcmp(variable,"pretty_print")) {
439 if(!strcmp(val,"true")) {
441 printf("pretty_print = true\n");
444 if(!strcmp(val,"false")) {
446 printf("pretty_print = false\n");
451 if(!strcmp(variable,"raw_print")) {
452 if(!strcmp(val,"true")) {
454 printf("raw_print = true\n");
457 if(!strcmp(val,"false")) {
459 printf("raw_print = false\n");
471 static int handle_print( char* words[]) {
474 if( (variable=words[1]) ) {
475 if(!strcmp(variable,"pretty_print")) {
477 printf("pretty_print = true\n");
480 printf("pretty_print = false\n");
485 if(!strcmp(variable,"login")) {
486 printf("login session = %s\n", login_session );
494 static int handle_router( char* words[] ) {
502 if( !strcmp(words[1],"query") ) {
504 if( words[2] && !strcmp(words[2],"servers") ) {
505 for(i=3; i < COMMAND_BUFSIZE - 3 && words[i]; i++ ) {
506 router_query_servers( words[i] );
519 static int handle_request( char* words[], int relay ) {
525 char* server = words[1];
526 char* method = words[2];
528 growing_buffer* buffer = NULL;
530 buffer = buffer_init(128);
531 buffer_add(buffer, "[");
532 for(i = 3; words[i] != NULL; i++ ) {
533 /* removes trailing semicolon if user accidentally enters it */
534 if( words[i][strlen(words[i])-1] == ';' )
535 words[i][strlen(words[i])-1] = '\0';
536 buffer_add( buffer, words[i] );
537 buffer_add(buffer, " ");
539 buffer_add(buffer, "]");
542 return send_request( server, method, buffer, relay );
548 int send_request( char* server,
549 char* method, growing_buffer* buffer, int relay ) {
550 if( server == NULL || method == NULL )
553 jsonObject* params = NULL;
555 if( buffer != NULL && buffer->n_used > 0 )
556 params = json_parse_string(buffer->buf);
558 if(!last_result || ! last_result->_result_content) {
559 printf("We're not going to call 'relay' with no result params\n");
563 jsonObject* o = jsonNewObject(NULL);
564 jsonObjectPush(o, last_result->_result_content );
570 if(buffer->n_used > 0 && params == NULL) {
571 fprintf(stderr, "JSON error detected, not executing\n");
575 osrf_app_session* session = osrf_app_client_session_init(server);
577 if(!osrf_app_session_connect(session)) {
578 osrfLogWarning( OSRF_LOG_MARK, "Unable to connect to remote service %s\n", server );
582 double start = get_timestamp_millis();
583 //int req_id = osrf_app_session_make_request( session, params, method, 1, NULL );
584 int req_id = osrf_app_session_make_req( session, params, method, 1, NULL );
587 osrf_message* omsg = osrf_app_session_request_recv( session, req_id, recv_timeout );
590 printf("\nReceived no data from server\n");
593 signal(SIGPIPE, SIG_IGN);
596 if(!is_from_script) less = popen( "less -EX", "w");
599 if( less == NULL ) { less = stdout; }
601 growing_buffer* resp_buffer = buffer_init(4096);
607 if(omsg->_result_content) {
609 osrf_message_free(last_result);
614 if( pretty_print && omsg->_result_content ) {
615 char* j = jsonObjectToJSON(omsg->_result_content);
616 //content = json_printer(j);
617 content = jsonFormatString(j);
620 content = jsonObjectGetString(omsg->_result_content);
622 printf( "\nReceived Data: %s\n", content );
629 sprintf( code, "%d", omsg->status_code );
630 buffer_add( resp_buffer, code );
632 printf( "\nReceived Exception:\nName: %s\nStatus: %s\nStatus: %s\n",
633 omsg->status_name, omsg->status_text, code );
640 if(omsg->_result_content) {
642 osrf_message_free(last_result);
647 if( pretty_print && omsg->_result_content ) {
648 char* j = jsonObjectToJSON(omsg->_result_content);
649 //content = json_printer(j);
650 content = jsonFormatString(j);
653 content = jsonObjectGetString(omsg->_result_content);
655 buffer_add( resp_buffer, "\nReceived Data: " );
656 buffer_add( resp_buffer, content );
657 buffer_add( resp_buffer, "\n" );
662 buffer_add( resp_buffer, "\nReceived Exception:\nName: " );
663 buffer_add( resp_buffer, omsg->status_name );
664 buffer_add( resp_buffer, "\nStatus: " );
665 buffer_add( resp_buffer, omsg->status_text );
666 buffer_add( resp_buffer, "\nStatus: " );
669 sprintf( code, "%d", omsg->status_code );
670 buffer_add( resp_buffer, code );
675 omsg = osrf_app_session_request_recv( session, req_id, recv_timeout );
679 double end = get_timestamp_millis();
681 fprintf( less, resp_buffer->buf );
682 buffer_free( resp_buffer );
683 fprintf( less, "\n------------------------------------\n");
684 if( osrf_app_session_request_complete( session, req_id ))
685 fprintf(less, "Request Completed Successfully\n");
688 fprintf(less, "Request Time in seconds: %.6f\n", end - start );
689 fprintf(less, "------------------------------------\n");
693 osrf_app_session_request_finish( session, req_id );
694 osrf_app_session_disconnect( session );
695 osrf_app_session_destroy( session );
704 static int handle_time( char* words[] ) {
711 printf( "%s\n", buf );
716 time_t epoch = (time_t)atoi( words[1] );
717 char* localtime = strdup( ctime( &epoch ) );
718 printf( "%s => %s", words[1], localtime );
730 static int router_query_servers( const char* router_server ) {
732 if( ! router_server || strlen(router_server) == 0 )
737 sprintf(rbuf,"router@%s/router", router_server );
739 transport_message* send =
740 message_init( "servers", NULL, NULL, rbuf, NULL );
741 message_set_router_info( send, NULL, NULL, NULL, "query", 0 );
743 client_send_message( client, send );
744 message_free( send );
746 transport_message* recv = client_recv( client, -1 );
748 fprintf(stderr, "NULL message received from router\n");
753 "---------------------------------------------------------------------------------\n"
754 "Received from 'server' query on %s\n"
755 "---------------------------------------------------------------------------------\n"
756 "original reg time | latest reg time | last used time | class | server\n"
757 "---------------------------------------------------------------------------------\n"
759 "---------------------------------------------------------------------------------\n"
760 , router_server, recv->body );
762 message_free( recv );
767 static int print_help( void ) {
770 "---------------------------------------------------------------------------------\n"
772 "---------------------------------------------------------------------------------\n"
773 "help - Display this message\n"
774 "!<command> [args] - Forks and runs the given command in the shell\n"
776 "time - Prints the current time\n"
777 "time <timestamp> - Formats seconds since epoch into readable format\n"
779 "set <variable> <value> - set a srfsh variable (e.g. set pretty_print true )\n"
780 "print <variable> - Displays the value of a srfsh variable\n"
781 "---------------------------------------------------------------------------------\n"
783 "router query servers <server1 [, server2, ...]>\n"
784 " - Returns stats on connected services\n"
787 "request <service> <method> [ <json formatted string of params> ]\n"
788 " - Anything passed in will be wrapped in a json array,\n"
789 " so add commas if there is more than one param\n"
792 "relay <service> <method>\n"
793 " - Performs the requested query using the last received result as the param\n"
796 "math_bench <num_batches> [0|1|2]\n"
797 " - 0 means don't reconnect, 1 means reconnect after each batch of 4, and\n"
798 " 2 means reconnect after every request\n"
800 "introspect <service>\n"
801 " - prints the API for the service\n"
804 "---------------------------------------------------------------------------------\n"
805 " Commands for Open-ILS\n"
806 "---------------------------------------------------------------------------------\n"
807 "login <username> <password>\n"
808 " - Logs into the 'server' and displays the session id\n"
809 " - To view the session id later, enter: print login\n"
810 "---------------------------------------------------------------------------------\n"
813 "Note: long output is piped through 'less'. To search in 'less', type: /<search>\n"
814 "---------------------------------------------------------------------------------\n"
823 static char* tabs(int count) {
824 growing_buffer* buf = buffer_init(24);
826 for(i=0;i!=count;i++)
827 buffer_add(buf, " ");
829 char* final = buffer_data( buf );
836 static int handle_math( char* words[] ) {
838 return do_math( atoi(words[1]), 0 );
843 static int do_math( int count, int style ) {
845 osrf_app_session* session = osrf_app_client_session_init( "opensrf.math" );
846 osrf_app_session_connect(session);
848 jsonObject* params = json_parse_string("[]");
849 jsonObjectPush(params,jsonNewObject("1"));
850 jsonObjectPush(params,jsonNewObject("2"));
852 char* methods[] = { "add", "sub", "mult", "div" };
853 char* answers[] = { "3", "-1", "2", "0.500000" };
855 float times[ count * 4 ];
856 memset(times,0,count*4);
859 for(k=0;k!=100;k++) {
866 fprintf(stderr,"\n\n");
870 for(i=0; i!= count; i++) {
873 for(j=0; j != 4; j++) {
877 double start = get_timestamp_millis();
878 int req_id = osrf_app_session_make_req( session, params, methods[j], 1, NULL );
879 osrf_message* omsg = osrf_app_session_request_recv( session, req_id, 5 );
880 double end = get_timestamp_millis();
882 times[(4*i) + j] = end - start;
886 if(omsg->_result_content) {
887 char* jsn = jsonObjectToJSON(omsg->_result_content);
888 if(!strcmp(jsn, answers[j]))
889 fprintf(stderr, "+");
891 fprintf(stderr, "\n![%s] - should be %s\n", jsn, answers[j] );
896 osrf_message_free(omsg);
898 } else { fprintf( stderr, "\nempty message for tt: %d\n", req_id ); }
900 osrf_app_session_request_finish( session, req_id );
903 osrf_app_session_disconnect( session );
906 fprintf(stderr,"\n");
910 osrf_app_session_disconnect( session );
913 osrf_app_session_destroy( session );
914 jsonObjectFree(params);
918 for(c=0; c!= count*4; c++)
921 float avg = total / (count*4);
922 fprintf(stderr, "\n Average round trip time: %f\n", avg );