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);
187 osrf_system_shutdown();
191 static int load_history( void ) {
193 char* home = getenv("HOME");
194 int l = strlen(home) + 24;
198 sprintf(fbuf,"%s/.srfsh_history",home);
199 history_file = strdup(fbuf);
201 if(!access(history_file, W_OK | R_OK )) {
202 history_length = 5000;
203 read_history(history_file);
209 static int parse_error( char* words[] ) {
214 growing_buffer * gbuf = buffer_init( 64 );
215 buffer_add( gbuf, *words );
217 buffer_add( gbuf, " " );
218 buffer_add( gbuf, *words );
220 fprintf( stderr, "???: %s\n", gbuf->buf );
228 static int parse_request( char* request ) {
230 if( request == NULL )
233 char* original_request = strdup( request );
234 char* words[COMMAND_BUFSIZE];
241 char* cur_tok = strtok( req, " " );
243 if( cur_tok == NULL )
245 free( original_request );
249 /* Load an array with pointers to */
250 /* the tokens as defined by strtok() */
252 while(cur_tok != NULL) {
253 if( i < COMMAND_BUFSIZE - 1 ) {
254 words[i++] = cur_tok;
255 cur_tok = strtok( NULL, " " );
257 fprintf( stderr, "Too many tokens in command\n" );
258 free( original_request );
265 /* pass off to the top level command */
266 if( !strcmp(words[0],"router") )
267 ret_val = handle_router( words );
269 else if( !strcmp(words[0],"time") )
270 ret_val = handle_time( words );
272 else if (!strcmp(words[0],"request"))
273 ret_val = handle_request( words, 0 );
275 else if (!strcmp(words[0],"relay"))
276 ret_val = handle_request( words, 1 );
278 else if (!strcmp(words[0],"help"))
279 ret_val = print_help();
281 else if (!strcmp(words[0],"set"))
282 ret_val = handle_set(words);
284 else if (!strcmp(words[0],"print"))
285 ret_val = handle_print(words);
287 else if (!strcmp(words[0],"math_bench"))
288 ret_val = handle_math(words);
290 else if (!strcmp(words[0],"introspect"))
291 ret_val = handle_introspect(words);
293 else if (!strcmp(words[0],"login"))
294 ret_val = handle_login(words);
296 else if (words[0][0] == '!') {
297 system( original_request + 1 );
301 free( original_request );
304 return parse_error( words );
310 static int handle_introspect(char* words[]) {
315 fprintf(stderr, "--> %s\n", words[1]);
317 // Build a command in a suitably-sized
318 // buffer and then parse it
322 static const char text[] = "request %s opensrf.system.method %s";
323 len = sizeof( text ) + strlen( words[1] ) + strlen( words[2] );
325 sprintf( buf, text, words[1], words[2] );
326 return parse_request( buf );
329 static const char text[] = "request %s opensrf.system.method.all";
330 len = sizeof( text ) + strlen( words[1] );
332 sprintf( buf, text, words[1] );
333 return parse_request( buf );
339 static int handle_login( char* words[]) {
341 if( words[1] && words[2]) {
343 char* username = words[1];
344 char* password = words[2];
345 char* type = words[3];
346 char* orgloc = words[4];
347 char* workstation = words[5];
348 int orgloci = (orgloc) ? atoi(orgloc) : 0;
349 if(!type) type = "opac";
351 char login_text[] = "request open-ils.auth open-ils.auth.authenticate.init \"%s\"";
352 size_t len = sizeof( login_text ) + strlen(username);
356 sprintf( buf, login_text, username );
360 if(last_result && last_result->_result_content) {
361 jsonObject* r = last_result->_result_content;
362 hash = jsonObjectGetString(r);
366 char* pass_buf = md5sum(password);
368 size_t both_len = strlen( hash ) + strlen( pass_buf ) + 1;
369 char both_buf[both_len];
371 sprintf(both_buf,"%s%s",hash, pass_buf);
373 char* mess_buf = md5sum(both_buf);
375 growing_buffer* argbuf = buffer_init(64);
377 "request open-ils.auth open-ils.auth.authenticate.complete "
378 "{ \"username\" : \"%s\", \"password\" : \"%s\"", username, mess_buf );
380 if(type) buffer_fadd( argbuf, ", \"type\" : \"%s\"", type );
381 if(orgloci) buffer_fadd( argbuf, ", \"org\" : %d", orgloci );
382 if(workstation) buffer_fadd( argbuf, ", \"workstation\" : \"%s\"", workstation);
383 buffer_add(argbuf, "}");
388 parse_request( argbuf->buf );
391 jsonObject* x = last_result->_result_content;
394 char* authtoken = jsonObjectGetString(
395 jsonObjectGetKey(jsonObjectGetKey(x,"payload"), "authtoken"));
396 authtime = jsonObjectGetNumber(
397 jsonObjectGetKey(jsonObjectGetKey(x,"payload"), "authtime"));
400 login_session = strdup(authtoken);
401 } else login_session = NULL;
403 else login_session = NULL;
405 printf("Login Session: %s. Session timeout: %f\n",
406 (login_session ? login_session : "(none)"), authtime );
415 static int handle_set( char* words[]) {
418 if( (variable=words[1]) ) {
421 if( (val=words[2]) ) {
423 if(!strcmp(variable,"pretty_print")) {
424 if(!strcmp(val,"true")) {
426 printf("pretty_print = true\n");
429 if(!strcmp(val,"false")) {
431 printf("pretty_print = false\n");
436 if(!strcmp(variable,"raw_print")) {
437 if(!strcmp(val,"true")) {
439 printf("raw_print = true\n");
442 if(!strcmp(val,"false")) {
444 printf("raw_print = false\n");
456 static int handle_print( char* words[]) {
459 if( (variable=words[1]) ) {
460 if(!strcmp(variable,"pretty_print")) {
462 printf("pretty_print = true\n");
465 printf("pretty_print = false\n");
470 if(!strcmp(variable,"raw_print")) {
472 printf("raw_print = true\n");
475 printf("raw_print = false\n");
480 if(!strcmp(variable,"login")) {
481 printf("login session = %s\n",
482 login_session ? login_session : "(none)" );
490 static int handle_router( char* words[] ) {
498 if( !strcmp(words[1],"query") ) {
500 if( words[2] && !strcmp(words[2],"servers") ) {
501 for(i=3; i < COMMAND_BUFSIZE - 3 && words[i]; i++ ) {
502 router_query_servers( words[i] );
515 static int handle_request( char* words[], int relay ) {
521 char* server = words[1];
522 char* method = words[2];
524 growing_buffer* buffer = NULL;
526 buffer = buffer_init(128);
527 buffer_add(buffer, "[");
528 for(i = 3; words[i] != NULL; i++ ) {
529 /* removes trailing semicolon if user accidentally enters it */
530 if( words[i][strlen(words[i])-1] == ';' )
531 words[i][strlen(words[i])-1] = '\0';
532 buffer_add( buffer, words[i] );
533 buffer_add(buffer, " ");
535 buffer_add(buffer, "]");
538 return send_request( server, method, buffer, relay );
544 int send_request( char* server,
545 char* method, growing_buffer* buffer, int relay ) {
546 if( server == NULL || method == NULL )
549 jsonObject* params = NULL;
551 if( buffer != NULL && buffer->n_used > 0 )
552 params = jsonParseString(buffer->buf);
554 if(!last_result || ! last_result->_result_content) {
555 printf("We're not going to call 'relay' with no result params\n");
559 jsonObject* o = jsonNewObject(NULL);
560 jsonObjectPush(o, last_result->_result_content );
566 if(buffer->n_used > 0 && params == NULL) {
567 fprintf(stderr, "JSON error detected, not executing\n");
571 osrf_app_session* session = osrf_app_client_session_init(server);
573 if(!osrf_app_session_connect(session)) {
574 osrfLogWarning( OSRF_LOG_MARK, "Unable to connect to remote service %s\n", server );
578 double start = get_timestamp_millis();
579 //int req_id = osrf_app_session_make_request( session, params, method, 1, NULL );
580 int req_id = osrf_app_session_make_req( session, params, method, 1, NULL );
583 osrf_message* omsg = osrf_app_session_request_recv( session, req_id, recv_timeout );
586 printf("\nReceived no data from server\n");
589 signal(SIGPIPE, SIG_IGN);
592 if(!is_from_script) less = popen( "less -EX", "w");
595 if( less == NULL ) { less = stdout; }
597 growing_buffer* resp_buffer = buffer_init(4096);
603 if(omsg->_result_content) {
605 osrf_message_free(last_result);
610 if( pretty_print && omsg->_result_content ) {
611 char* j = jsonObjectToJSON(omsg->_result_content);
612 //content = json_printer(j);
613 content = jsonFormatString(j);
616 content = jsonObjectGetString(omsg->_result_content);
618 printf( "\nReceived Data: %s\n", content );
625 sprintf( code, "%d", omsg->status_code );
626 buffer_add( resp_buffer, code );
628 printf( "\nReceived Exception:\nName: %s\nStatus: %s\nStatus: %s\n",
629 omsg->status_name, omsg->status_text, code );
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 buffer_add( resp_buffer, "\nReceived Data: " );
652 buffer_add( resp_buffer, content );
653 buffer_add( resp_buffer, "\n" );
658 buffer_add( resp_buffer, "\nReceived Exception:\nName: " );
659 buffer_add( resp_buffer, omsg->status_name );
660 buffer_add( resp_buffer, "\nStatus: " );
661 buffer_add( resp_buffer, omsg->status_text );
662 buffer_add( resp_buffer, "\nStatus: " );
665 sprintf( code, "%d", omsg->status_code );
666 buffer_add( resp_buffer, code );
671 omsg = osrf_app_session_request_recv( session, req_id, recv_timeout );
675 double end = get_timestamp_millis();
677 fprintf( less, resp_buffer->buf );
678 buffer_free( resp_buffer );
679 fprintf( less, "\n------------------------------------\n");
680 if( osrf_app_session_request_complete( session, req_id ))
681 fprintf(less, "Request Completed Successfully\n");
684 fprintf(less, "Request Time in seconds: %.6f\n", end - start );
685 fprintf(less, "------------------------------------\n");
689 osrf_app_session_request_finish( session, req_id );
690 osrf_app_session_disconnect( session );
691 osrf_app_session_destroy( session );
699 static int handle_time( char* words[] ) {
701 printf("%f\n", get_timestamp_millis());
703 time_t epoch = (time_t) atoi(words[1]);
704 printf("%s", ctime(&epoch));
711 static int router_query_servers( const char* router_server ) {
713 if( ! router_server || strlen(router_server) == 0 )
718 sprintf(rbuf,"router@%s/router", router_server );
720 transport_message* send =
721 message_init( "servers", NULL, NULL, rbuf, NULL );
722 message_set_router_info( send, NULL, NULL, NULL, "query", 0 );
724 client_send_message( client, send );
725 message_free( send );
727 transport_message* recv = client_recv( client, -1 );
729 fprintf(stderr, "NULL message received from router\n");
734 "---------------------------------------------------------------------------------\n"
735 "Received from 'server' query on %s\n"
736 "---------------------------------------------------------------------------------\n"
737 "original reg time | latest reg time | last used time | class | server\n"
738 "---------------------------------------------------------------------------------\n"
740 "---------------------------------------------------------------------------------\n"
741 , router_server, recv->body );
743 message_free( recv );
748 static int print_help( void ) {
751 "---------------------------------------------------------------------------------\n"
753 "---------------------------------------------------------------------------------\n"
754 "help - Display this message\n"
755 "!<command> [args] - Forks and runs the given command in the shell\n"
757 "time - Prints the current time\n"
758 "time <timestamp> - Formats seconds since epoch into readable format\n"
760 "set <variable> <value> - set a srfsh variable (e.g. set pretty_print true )\n"
761 "print <variable> - Displays the value of a srfsh variable\n"
762 "---------------------------------------------------------------------------------\n"
764 "router query servers <server1 [, server2, ...]>\n"
765 " - Returns stats on connected services\n"
768 "request <service> <method> [ <json formatted string of params> ]\n"
769 " - Anything passed in will be wrapped in a json array,\n"
770 " so add commas if there is more than one param\n"
773 "relay <service> <method>\n"
774 " - Performs the requested query using the last received result as the param\n"
777 "math_bench <num_batches> [0|1|2]\n"
778 " - 0 means don't reconnect, 1 means reconnect after each batch of 4, and\n"
779 " 2 means reconnect after every request\n"
781 "introspect <service>\n"
782 " - prints the API for the service\n"
785 "---------------------------------------------------------------------------------\n"
786 " Commands for Open-ILS\n"
787 "---------------------------------------------------------------------------------\n"
788 "login <username> <password>\n"
789 " - Logs into the 'server' and displays the session id\n"
790 " - To view the session id later, enter: print login\n"
791 "---------------------------------------------------------------------------------\n"
794 "Note: long output is piped through 'less'. To search in 'less', type: /<search>\n"
795 "---------------------------------------------------------------------------------\n"
804 static char* tabs(int count) {
805 growing_buffer* buf = buffer_init(24);
807 for(i=0;i!=count;i++)
808 buffer_add(buf, " ");
810 char* final = buffer_data( buf );
817 static int handle_math( char* words[] ) {
819 return do_math( atoi(words[1]), 0 );
824 static int do_math( int count, int style ) {
826 osrf_app_session* session = osrf_app_client_session_init( "opensrf.math" );
827 osrf_app_session_connect(session);
829 jsonObject* params = jsonParseString("[]");
830 jsonObjectPush(params,jsonNewObject("1"));
831 jsonObjectPush(params,jsonNewObject("2"));
833 char* methods[] = { "add", "sub", "mult", "div" };
834 char* answers[] = { "3", "-1", "2", "0.500000" };
836 float times[ count * 4 ];
837 memset(times,0,count*4);
840 for(k=0;k!=100;k++) {
847 fprintf(stderr,"\n\n");
851 for(i=0; i!= count; i++) {
854 for(j=0; j != 4; j++) {
858 double start = get_timestamp_millis();
859 int req_id = osrf_app_session_make_req( session, params, methods[j], 1, NULL );
860 osrf_message* omsg = osrf_app_session_request_recv( session, req_id, 5 );
861 double end = get_timestamp_millis();
863 times[(4*i) + j] = end - start;
867 if(omsg->_result_content) {
868 char* jsn = jsonObjectToJSON(omsg->_result_content);
869 if(!strcmp(jsn, answers[j]))
870 fprintf(stderr, "+");
872 fprintf(stderr, "\n![%s] - should be %s\n", jsn, answers[j] );
877 osrf_message_free(omsg);
879 } else { fprintf( stderr, "\nempty message for tt: %d\n", req_id ); }
881 osrf_app_session_request_finish( session, req_id );
884 osrf_app_session_disconnect( session );
887 fprintf(stderr,"\n");
891 osrf_app_session_disconnect( session );
894 osrf_app_session_destroy( session );
895 jsonObjectFree(params);
899 for(c=0; c!= count*4; c++)
902 float avg = total / (count*4);
903 fprintf(stderr, "\n Average round trip time: %f\n", avg );