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_set( char* words[]);
54 static int handle_print( char* words[]);
55 static int send_request( char* server,
56 char* method, growing_buffer* buffer, int relay );
57 static int parse_error( char* words[] );
58 static int router_query_servers( const char* server );
59 static int print_help( void );
61 //static int srfsh_client_connect();
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( void );
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;
75 int main( int argc, char* argv[] ) {
77 /* --------------------------------------------- */
78 /* see if they have a .srfsh.xml in their home directory */
79 char* home = getenv("HOME");
80 int l = strlen(home) + 36;
83 sprintf(fbuf,"%s/.srfsh.xml",home);
85 if(!access(fbuf, R_OK)) {
86 if( ! osrf_system_bootstrap_client(fbuf, "srfsh") ) {
87 fprintf(stderr,"Unable to bootstrap client for requests\n");
88 osrfLogError( OSRF_LOG_MARK, "Unable to bootstrap client for requests");
93 fprintf(stderr,"No Config file found at %s\n", fbuf );
98 /* for now.. the first arg is used as a script file for processing */
100 if( (f = open(argv[1], O_RDONLY)) == -1 ) {
101 osrfLogError( OSRF_LOG_MARK, "Unable to open file %s for reading, exiting...", argv[1]);
105 if(dup2(f, STDIN_FILENO) == -1) {
106 osrfLogError( OSRF_LOG_MARK, "Unable to duplicate STDIN, exiting...");
114 /* --------------------------------------------- */
118 client = osrf_system_get_transport_client();
120 /* main process loop */
122 while((request=readline(prompt))) {
124 if( !strcasecmp(request, "exit") || !strcasecmp(request,"quit"))
127 char* req_copy = strdup(request);
129 parse_request( req_copy );
130 if( request && strlen(request) > 1 ) {
131 add_history(request);
141 if(history_file != NULL )
142 write_history(history_file);
146 osrf_system_shutdown();
151 static void sig_child_handler( int s ) {
157 void sig_int_handler( int s ) {
160 signal(SIGINT,sig_int_handler);
164 static int load_history( void ) {
166 char* home = getenv("HOME");
167 int l = strlen(home) + 24;
171 sprintf(fbuf,"%s/.srfsh_history",home);
172 history_file = strdup(fbuf);
174 if(!access(history_file, W_OK | R_OK )) {
175 history_length = 5000;
176 read_history(history_file);
182 static int parse_error( char* words[] ) {
187 growing_buffer * gbuf = buffer_init( 64 );
188 buffer_add( gbuf, *words );
190 buffer_add( gbuf, " " );
191 buffer_add( gbuf, *words );
193 fprintf( stderr, "???: %s\n", gbuf->buf );
201 static int parse_request( char* request ) {
203 if( request == NULL )
206 char* original_request = strdup( request );
207 char* words[COMMAND_BUFSIZE];
214 char* cur_tok = strtok( req, " " );
216 if( cur_tok == NULL )
218 free( original_request );
222 /* Load an array with pointers to */
223 /* the tokens as defined by strtok() */
225 while(cur_tok != NULL) {
226 if( i < COMMAND_BUFSIZE - 1 ) {
227 words[i++] = cur_tok;
228 cur_tok = strtok( NULL, " " );
230 fprintf( stderr, "Too many tokens in command\n" );
231 free( original_request );
238 /* pass off to the top level command */
239 if( !strcmp(words[0],"router") )
240 ret_val = handle_router( words );
243 else if( !strcmp(words[0],"time") )
244 ret_val = handle_time( words );
247 else if (!strcmp(words[0],"request"))
248 ret_val = handle_request( words, 0 );
250 else if (!strcmp(words[0],"relay"))
251 ret_val = handle_request( words, 1 );
253 else if (!strcmp(words[0],"help"))
254 ret_val = print_help();
256 else if (!strcmp(words[0],"set"))
257 ret_val = handle_set(words);
259 else if (!strcmp(words[0],"print"))
260 ret_val = handle_print(words);
262 else if (!strcmp(words[0],"math_bench"))
263 ret_val = handle_math(words);
265 else if (!strcmp(words[0],"introspect"))
266 ret_val = handle_introspect(words);
268 else if (!strcmp(words[0],"login"))
269 ret_val = handle_login(words);
271 else if (words[0][0] == '!') {
272 system( original_request + 1 );
276 free( original_request );
279 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] );
479 static int handle_request( char* words[], int relay ) {
485 char* server = words[1];
486 char* method = words[2];
488 growing_buffer* buffer = NULL;
490 buffer = buffer_init(128);
491 buffer_add(buffer, "[");
492 for(i = 3; words[i] != NULL; i++ ) {
493 /* removes trailing semicolon if user accidentally enters it */
494 if( words[i][strlen(words[i])-1] == ';' )
495 words[i][strlen(words[i])-1] = '\0';
496 buffer_add( buffer, words[i] );
497 buffer_add(buffer, " ");
499 buffer_add(buffer, "]");
502 return send_request( server, method, buffer, relay );
508 int send_request( char* server,
509 char* method, growing_buffer* buffer, int relay ) {
510 if( server == NULL || method == NULL )
513 jsonObject* params = NULL;
515 if( buffer != NULL && buffer->n_used > 0 )
516 params = json_parse_string(buffer->buf);
518 if(!last_result || ! last_result->_result_content) {
519 printf("We're not going to call 'relay' with no result params\n");
523 jsonObject* o = jsonNewObject(NULL);
524 jsonObjectPush(o, last_result->_result_content );
530 if(buffer->n_used > 0 && params == NULL) {
531 fprintf(stderr, "JSON error detected, not executing\n");
535 osrf_app_session* session = osrf_app_client_session_init(server);
537 if(!osrf_app_session_connect(session)) {
538 osrfLogWarning( OSRF_LOG_MARK, "Unable to connect to remote service %s\n", server );
542 double start = get_timestamp_millis();
543 //int req_id = osrf_app_session_make_request( session, params, method, 1, NULL );
544 int req_id = osrf_app_session_make_req( session, params, method, 1, NULL );
547 osrf_message* omsg = osrf_app_session_request_recv( session, req_id, recv_timeout );
550 printf("\nReceived no data from server\n");
553 signal(SIGPIPE, SIG_IGN);
556 if(!is_from_script) less = popen( "less -EX", "w");
559 if( less == NULL ) { less = stdout; }
561 growing_buffer* resp_buffer = buffer_init(4096);
567 if(omsg->_result_content) {
569 osrf_message_free(last_result);
574 if( pretty_print && omsg->_result_content ) {
575 char* j = jsonObjectToJSON(omsg->_result_content);
576 //content = json_printer(j);
577 content = jsonFormatString(j);
580 content = jsonObjectGetString(omsg->_result_content);
582 printf( "\nReceived Data: %s\n", content );
589 sprintf( code, "%d", omsg->status_code );
590 buffer_add( resp_buffer, code );
592 printf( "\nReceived Exception:\nName: %s\nStatus: %s\nStatus: %s\n",
593 omsg->status_name, omsg->status_text, code );
600 if(omsg->_result_content) {
602 osrf_message_free(last_result);
607 if( pretty_print && omsg->_result_content ) {
608 char* j = jsonObjectToJSON(omsg->_result_content);
609 //content = json_printer(j);
610 content = jsonFormatString(j);
613 content = jsonObjectGetString(omsg->_result_content);
615 buffer_add( resp_buffer, "\nReceived Data: " );
616 buffer_add( resp_buffer, content );
617 buffer_add( resp_buffer, "\n" );
622 buffer_add( resp_buffer, "\nReceived Exception:\nName: " );
623 buffer_add( resp_buffer, omsg->status_name );
624 buffer_add( resp_buffer, "\nStatus: " );
625 buffer_add( resp_buffer, omsg->status_text );
626 buffer_add( resp_buffer, "\nStatus: " );
629 sprintf( code, "%d", omsg->status_code );
630 buffer_add( resp_buffer, code );
635 omsg = osrf_app_session_request_recv( session, req_id, recv_timeout );
639 double end = get_timestamp_millis();
641 fprintf( less, resp_buffer->buf );
642 buffer_free( resp_buffer );
643 fprintf( less, "\n------------------------------------\n");
644 if( osrf_app_session_request_complete( session, req_id ))
645 fprintf(less, "Request Completed Successfully\n");
648 fprintf(less, "Request Time in seconds: %.6f\n", end - start );
649 fprintf(less, "------------------------------------\n");
653 osrf_app_session_request_finish( session, req_id );
654 osrf_app_session_disconnect( session );
655 osrf_app_session_destroy( session );
664 static int handle_time( char* words[] ) {
671 printf( "%s\n", buf );
676 time_t epoch = (time_t)atoi( words[1] );
677 char* localtime = strdup( ctime( &epoch ) );
678 printf( "%s => %s", words[1], localtime );
690 static int router_query_servers( const char* router_server ) {
692 if( ! router_server || strlen(router_server) == 0 )
697 sprintf(rbuf,"router@%s/router", router_server );
699 transport_message* send =
700 message_init( "servers", NULL, NULL, rbuf, NULL );
701 message_set_router_info( send, NULL, NULL, NULL, "query", 0 );
703 client_send_message( client, send );
704 message_free( send );
706 transport_message* recv = client_recv( client, -1 );
708 fprintf(stderr, "NULL message received from router\n");
713 "---------------------------------------------------------------------------------\n"
714 "Received from 'server' query on %s\n"
715 "---------------------------------------------------------------------------------\n"
716 "original reg time | latest reg time | last used time | class | server\n"
717 "---------------------------------------------------------------------------------\n"
719 "---------------------------------------------------------------------------------\n"
720 , router_server, recv->body );
722 message_free( recv );
727 static int print_help( void ) {
730 "---------------------------------------------------------------------------------\n"
732 "---------------------------------------------------------------------------------\n"
733 "help - Display this message\n"
734 "!<command> [args] - Forks and runs the given command in the shell\n"
736 "time - Prints the current time\n"
737 "time <timestamp> - Formats seconds since epoch into readable format\n"
739 "set <variable> <value> - set a srfsh variable (e.g. set pretty_print true )\n"
740 "print <variable> - Displays the value of a srfsh variable\n"
741 "---------------------------------------------------------------------------------\n"
743 "router query servers <server1 [, server2, ...]>\n"
744 " - Returns stats on connected services\n"
747 "request <service> <method> [ <json formatted string of params> ]\n"
748 " - Anything passed in will be wrapped in a json array,\n"
749 " so add commas if there is more than one param\n"
752 "relay <service> <method>\n"
753 " - Performs the requested query using the last received result as the param\n"
756 "math_bench <num_batches> [0|1|2]\n"
757 " - 0 means don't reconnect, 1 means reconnect after each batch of 4, and\n"
758 " 2 means reconnect after every request\n"
760 "introspect <service>\n"
761 " - prints the API for the service\n"
764 "---------------------------------------------------------------------------------\n"
765 " Commands for Open-ILS\n"
766 "---------------------------------------------------------------------------------\n"
767 "login <username> <password>\n"
768 " - Logs into the 'server' and displays the session id\n"
769 " - To view the session id later, enter: print login\n"
770 "---------------------------------------------------------------------------------\n"
773 "Note: long output is piped through 'less'. To search in 'less', type: /<search>\n"
774 "---------------------------------------------------------------------------------\n"
783 static char* tabs(int count) {
784 growing_buffer* buf = buffer_init(24);
786 for(i=0;i!=count;i++)
787 buffer_add(buf, " ");
789 char* final = buffer_data( buf );
796 static int handle_math( char* words[] ) {
798 return do_math( atoi(words[1]), 0 );
803 static int do_math( int count, int style ) {
805 osrf_app_session* session = osrf_app_client_session_init( "opensrf.math" );
806 osrf_app_session_connect(session);
808 jsonObject* params = json_parse_string("[]");
809 jsonObjectPush(params,jsonNewObject("1"));
810 jsonObjectPush(params,jsonNewObject("2"));
812 char* methods[] = { "add", "sub", "mult", "div" };
813 char* answers[] = { "3", "-1", "2", "0.500000" };
815 float times[ count * 4 ];
816 memset(times,0,count*4);
819 for(k=0;k!=100;k++) {
826 fprintf(stderr,"\n\n");
830 for(i=0; i!= count; i++) {
833 for(j=0; j != 4; j++) {
837 double start = get_timestamp_millis();
838 int req_id = osrf_app_session_make_req( session, params, methods[j], 1, NULL );
839 osrf_message* omsg = osrf_app_session_request_recv( session, req_id, 5 );
840 double end = get_timestamp_millis();
842 times[(4*i) + j] = end - start;
846 if(omsg->_result_content) {
847 char* jsn = jsonObjectToJSON(omsg->_result_content);
848 if(!strcmp(jsn, answers[j]))
849 fprintf(stderr, "+");
851 fprintf(stderr, "\n![%s] - should be %s\n", jsn, answers[j] );
856 osrf_message_free(omsg);
858 } else { fprintf( stderr, "\nempty message for tt: %d\n", req_id ); }
860 osrf_app_session_request_finish( session, req_id );
863 osrf_app_session_disconnect( session );
866 fprintf(stderr,"\n");
870 osrf_app_session_disconnect( session );
873 osrf_app_session_destroy( session );
874 jsonObjectFree(params);
878 for(c=0; c!= count*4; c++)
881 float avg = total / (count*4);
882 fprintf(stderr, "\n Average round trip time: %f\n", avg );