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 = calloc(COMMAND_BUFSIZE, sizeof(char*));
214 char* cur_tok = strtok( req, " " );
216 if( cur_tok == NULL )
218 free( original_request );
223 /* Load an array with pointers to */
224 /* the tokens as defined by strtok() */
226 while(cur_tok != NULL) {
227 if( i < COMMAND_BUFSIZE - 1 ) {
228 words[i++] = cur_tok;
229 cur_tok = strtok( NULL, " " );
231 fprintf( stderr, "Too many tokens in command\n" );
232 free( original_request );
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 system( original_request + 1 );
280 ret_val = parse_error( words );
284 free( original_request );
290 static int handle_introspect(char* words[]) {
292 if(words[1] && words[2]) {
293 fprintf(stderr, "--> %s\n", words[1]);
296 sprintf( buf, "request %s opensrf.system.method %s", words[1], words[2] );
297 return parse_request( buf );
302 fprintf(stderr, "--> %s\n", words[1]);
305 sprintf( buf, "request %s opensrf.system.method.all", words[1] );
306 return parse_request( buf );
314 static int handle_login( char* words[]) {
316 if( words[1] && words[2]) {
318 char* username = words[1];
319 char* password = words[2];
320 char* type = words[3];
321 char* orgloc = words[4];
322 char* workstation = words[5];
323 int orgloci = (orgloc) ? atoi(orgloc) : 0;
324 if(!type) type = "opac";
333 "request open-ils.auth open-ils.auth.authenticate.init \"%s\"", username );
337 if(last_result && last_result->_result_content) {
338 jsonObject* r = last_result->_result_content;
339 hash = jsonObjectGetString(r);
343 char* pass_buf = md5sum(password);
346 memset(both_buf,0,256);
347 sprintf(both_buf,"%s%s",hash, pass_buf);
349 char* mess_buf = md5sum(both_buf);
352 sprintf( buf2, "request open-ils.auth open-ils.auth.authenticate.complete "
353 "{ \"username\" : \"%s\", \"password\" : \"%s\", "
354 "\"type\" : \"%s\", \"org\" : %d, \"workstation\": \"%s\"}",
355 username, mess_buf, type, orgloci, workstation );
358 growing_buffer* argbuf = buffer_init(64);
360 "request open-ils.auth open-ils.auth.authenticate.complete "
361 "{ \"username\" : \"%s\", \"password\" : \"%s\"", username, mess_buf );
363 if(type) buffer_fadd( argbuf, ", \"type\" : \"%s\"", type );
364 if(orgloci) buffer_fadd( argbuf, ", \"org\" : %d", orgloci );
365 if(workstation) buffer_fadd( argbuf, ", \"workstation\" : \"%s\"", workstation);
366 buffer_add(argbuf, "}");
371 parse_request( argbuf->buf );
374 jsonObject* x = last_result->_result_content;
377 char* authtoken = jsonObjectGetString(
378 jsonObjectGetKey(jsonObjectGetKey(x,"payload"), "authtoken"));
379 authtime = jsonObjectGetNumber(
380 jsonObjectGetKey(jsonObjectGetKey(x,"payload"), "authtime"));
381 if(authtoken) login_session = strdup(authtoken);
382 else login_session = NULL;
384 else login_session = NULL;
386 printf("Login Session: %s. Session timeout: %f\n", login_session, authtime );
395 static int handle_set( char* words[]) {
398 if( (variable=words[1]) ) {
401 if( (val=words[2]) ) {
403 if(!strcmp(variable,"pretty_print")) {
404 if(!strcmp(val,"true")) {
406 printf("pretty_print = true\n");
409 if(!strcmp(val,"false")) {
411 printf("pretty_print = false\n");
416 if(!strcmp(variable,"raw_print")) {
417 if(!strcmp(val,"true")) {
419 printf("raw_print = true\n");
422 if(!strcmp(val,"false")) {
424 printf("raw_print = false\n");
436 static int handle_print( char* words[]) {
439 if( (variable=words[1]) ) {
440 if(!strcmp(variable,"pretty_print")) {
442 printf("pretty_print = true\n");
445 printf("pretty_print = false\n");
450 if(!strcmp(variable,"login")) {
451 printf("login session = %s\n", login_session );
459 static int handle_router( char* words[] ) {
467 if( !strcmp(words[1],"query") ) {
469 if( words[2] && !strcmp(words[2],"servers") ) {
470 for(i=3; i < COMMAND_BUFSIZE - 3 && words[i]; i++ ) {
471 router_query_servers( words[i] );
484 static int handle_request( char* words[], int relay ) {
490 char* server = words[1];
491 char* method = words[2];
493 growing_buffer* buffer = NULL;
495 buffer = buffer_init(128);
496 buffer_add(buffer, "[");
497 for(i = 3; words[i] != NULL; i++ ) {
498 /* removes trailing semicolon if user accidentally enters it */
499 if( words[i][strlen(words[i])-1] == ';' )
500 words[i][strlen(words[i])-1] = '\0';
501 buffer_add( buffer, words[i] );
502 buffer_add(buffer, " ");
504 buffer_add(buffer, "]");
507 return send_request( server, method, buffer, relay );
513 int send_request( char* server,
514 char* method, growing_buffer* buffer, int relay ) {
515 if( server == NULL || method == NULL )
518 jsonObject* params = NULL;
520 if( buffer != NULL && buffer->n_used > 0 )
521 params = json_parse_string(buffer->buf);
523 if(!last_result || ! last_result->_result_content) {
524 printf("We're not going to call 'relay' with no result params\n");
528 jsonObject* o = jsonNewObject(NULL);
529 jsonObjectPush(o, last_result->_result_content );
535 if(buffer->n_used > 0 && params == NULL) {
536 fprintf(stderr, "JSON error detected, not executing\n");
540 osrf_app_session* session = osrf_app_client_session_init(server);
542 if(!osrf_app_session_connect(session)) {
543 osrfLogWarning( OSRF_LOG_MARK, "Unable to connect to remote service %s\n", server );
547 double start = get_timestamp_millis();
548 //int req_id = osrf_app_session_make_request( session, params, method, 1, NULL );
549 int req_id = osrf_app_session_make_req( session, params, method, 1, NULL );
552 osrf_message* omsg = osrf_app_session_request_recv( session, req_id, recv_timeout );
555 printf("\nReceived no data from server\n");
558 signal(SIGPIPE, SIG_IGN);
561 if(!is_from_script) less = popen( "less -EX", "w");
564 if( less == NULL ) { less = stdout; }
566 growing_buffer* resp_buffer = buffer_init(4096);
572 if(omsg->_result_content) {
574 osrf_message_free(last_result);
579 if( pretty_print && omsg->_result_content ) {
580 char* j = jsonObjectToJSON(omsg->_result_content);
581 //content = json_printer(j);
582 content = jsonFormatString(j);
585 content = jsonObjectGetString(omsg->_result_content);
587 printf( "\nReceived Data: %s\n", content );
594 sprintf( code, "%d", omsg->status_code );
595 buffer_add( resp_buffer, code );
597 printf( "\nReceived Exception:\nName: %s\nStatus: %s\nStatus: %s\n",
598 omsg->status_name, omsg->status_text, code );
605 if(omsg->_result_content) {
607 osrf_message_free(last_result);
612 if( pretty_print && omsg->_result_content ) {
613 char* j = jsonObjectToJSON(omsg->_result_content);
614 //content = json_printer(j);
615 content = jsonFormatString(j);
618 content = jsonObjectGetString(omsg->_result_content);
620 buffer_add( resp_buffer, "\nReceived Data: " );
621 buffer_add( resp_buffer, content );
622 buffer_add( resp_buffer, "\n" );
627 buffer_add( resp_buffer, "\nReceived Exception:\nName: " );
628 buffer_add( resp_buffer, omsg->status_name );
629 buffer_add( resp_buffer, "\nStatus: " );
630 buffer_add( resp_buffer, omsg->status_text );
631 buffer_add( resp_buffer, "\nStatus: " );
634 sprintf( code, "%d", omsg->status_code );
635 buffer_add( resp_buffer, code );
640 omsg = osrf_app_session_request_recv( session, req_id, recv_timeout );
644 double end = get_timestamp_millis();
646 fprintf( less, resp_buffer->buf );
647 buffer_free( resp_buffer );
648 fprintf( less, "\n------------------------------------\n");
649 if( osrf_app_session_request_complete( session, req_id ))
650 fprintf(less, "Request Completed Successfully\n");
653 fprintf(less, "Request Time in seconds: %.6f\n", end - start );
654 fprintf(less, "------------------------------------\n");
658 osrf_app_session_request_finish( session, req_id );
659 osrf_app_session_disconnect( session );
660 osrf_app_session_destroy( session );
669 static int handle_time( char* words[] ) {
676 printf( "%s\n", buf );
681 time_t epoch = (time_t)atoi( words[1] );
682 char* localtime = strdup( ctime( &epoch ) );
683 printf( "%s => %s", words[1], localtime );
695 static int router_query_servers( const char* router_server ) {
697 if( ! router_server || strlen(router_server) == 0 )
702 sprintf(rbuf,"router@%s/router", router_server );
704 transport_message* send =
705 message_init( "servers", NULL, NULL, rbuf, NULL );
706 message_set_router_info( send, NULL, NULL, NULL, "query", 0 );
708 client_send_message( client, send );
709 message_free( send );
711 transport_message* recv = client_recv( client, -1 );
713 fprintf(stderr, "NULL message received from router\n");
718 "---------------------------------------------------------------------------------\n"
719 "Received from 'server' query on %s\n"
720 "---------------------------------------------------------------------------------\n"
721 "original reg time | latest reg time | last used time | class | server\n"
722 "---------------------------------------------------------------------------------\n"
724 "---------------------------------------------------------------------------------\n"
725 , router_server, recv->body );
727 message_free( recv );
732 static int print_help( void ) {
735 "---------------------------------------------------------------------------------\n"
737 "---------------------------------------------------------------------------------\n"
738 "help - Display this message\n"
739 "!<command> [args] - Forks and runs the given command in the shell\n"
741 "time - Prints the current time\n"
742 "time <timestamp> - Formats seconds since epoch into readable format\n"
744 "set <variable> <value> - set a srfsh variable (e.g. set pretty_print true )\n"
745 "print <variable> - Displays the value of a srfsh variable\n"
746 "---------------------------------------------------------------------------------\n"
748 "router query servers <server1 [, server2, ...]>\n"
749 " - Returns stats on connected services\n"
752 "request <service> <method> [ <json formatted string of params> ]\n"
753 " - Anything passed in will be wrapped in a json array,\n"
754 " so add commas if there is more than one param\n"
757 "relay <service> <method>\n"
758 " - Performs the requested query using the last received result as the param\n"
761 "math_bench <num_batches> [0|1|2]\n"
762 " - 0 means don't reconnect, 1 means reconnect after each batch of 4, and\n"
763 " 2 means reconnect after every request\n"
765 "introspect <service>\n"
766 " - prints the API for the service\n"
769 "---------------------------------------------------------------------------------\n"
770 " Commands for Open-ILS\n"
771 "---------------------------------------------------------------------------------\n"
772 "login <username> <password>\n"
773 " - Logs into the 'server' and displays the session id\n"
774 " - To view the session id later, enter: print login\n"
775 "---------------------------------------------------------------------------------\n"
778 "Note: long output is piped through 'less'. To search in 'less', type: /<search>\n"
779 "---------------------------------------------------------------------------------\n"
788 static char* tabs(int count) {
789 growing_buffer* buf = buffer_init(24);
791 for(i=0;i!=count;i++)
792 buffer_add(buf, " ");
794 char* final = buffer_data( buf );
801 static int handle_math( char* words[] ) {
803 return do_math( atoi(words[1]), 0 );
808 static int do_math( int count, int style ) {
810 osrf_app_session* session = osrf_app_client_session_init( "opensrf.math" );
811 osrf_app_session_connect(session);
813 jsonObject* params = json_parse_string("[]");
814 jsonObjectPush(params,jsonNewObject("1"));
815 jsonObjectPush(params,jsonNewObject("2"));
817 char* methods[] = { "add", "sub", "mult", "div" };
818 char* answers[] = { "3", "-1", "2", "0.500000" };
820 float times[ count * 4 ];
821 memset(times,0,count*4);
824 for(k=0;k!=100;k++) {
831 fprintf(stderr,"\n\n");
835 for(i=0; i!= count; i++) {
838 for(j=0; j != 4; j++) {
842 double start = get_timestamp_millis();
843 int req_id = osrf_app_session_make_req( session, params, methods[j], 1, NULL );
844 osrf_message* omsg = osrf_app_session_request_recv( session, req_id, 5 );
845 double end = get_timestamp_millis();
847 times[(4*i) + j] = end - start;
851 if(omsg->_result_content) {
852 char* jsn = jsonObjectToJSON(omsg->_result_content);
853 if(!strcmp(jsn, answers[j]))
854 fprintf(stderr, "+");
856 fprintf(stderr, "\n![%s] - should be %s\n", jsn, answers[j] );
861 osrf_message_free(omsg);
863 } else { fprintf( stderr, "\nempty message for tt: %d\n", req_id ); }
865 osrf_app_session_request_finish( session, req_id );
868 osrf_app_session_disconnect( session );
871 fprintf(stderr,"\n");
875 osrf_app_session_disconnect( session );
878 osrf_app_session_destroy( session );
879 jsonObjectFree(params);
883 for(c=0; c!= count*4; c++)
886 float avg = total / (count*4);
887 fprintf(stderr, "\n Average round trip time: %f\n", avg );