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 osrfMessage* 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 char* get_request( void );
68 static int load_history( void );
69 static int handle_math( char* words[] );
70 static int do_math( int count, int style );
71 static int handle_introspect(char* words[]);
72 static int handle_login( char* words[]);
73 static int handle_open( char* words[]);
74 static int handle_close( char* words[]);
75 static void close_all_sessions( void );
77 static int recv_timeout = 120;
78 static int is_from_script = 0;
80 static osrfHash* server_hash = NULL;
82 int main( int argc, char* argv[] ) {
84 /* --------------------------------------------- */
85 /* see if they have a .srfsh.xml in their home directory */
86 char* home = getenv("HOME");
87 int l = strlen(home) + 36;
89 snprintf(fbuf, sizeof(fbuf), "%s/.srfsh.xml", home);
91 if(!access(fbuf, R_OK)) {
92 if( ! osrf_system_bootstrap_client(fbuf, "srfsh") ) {
93 fprintf(stderr,"Unable to bootstrap client for requests\n");
94 osrfLogError( OSRF_LOG_MARK, "Unable to bootstrap client for requests");
99 fprintf(stderr,"No Config file found at %s\n", fbuf );
104 /* for now.. the first arg is used as a script file for processing */
106 if( (f = open(argv[1], O_RDONLY)) == -1 ) {
107 osrfLogError( OSRF_LOG_MARK, "Unable to open file %s for reading, exiting...", argv[1]);
111 if(dup2(f, STDIN_FILENO) == -1) {
112 osrfLogError( OSRF_LOG_MARK, "Unable to duplicate STDIN, exiting...");
120 /* --------------------------------------------- */
123 client = osrfSystemGetTransportClient();
125 // Disable special treatment for tabs by readline
126 // (by default they invoke command completion, which
127 // is not useful for srfsh)
128 rl_bind_key( '\t', rl_insert );
130 /* main process loop */
131 int newline_needed = 1; /* used as boolean */
133 while( (request = get_request()) ) {
135 // Find first non-whitespace character
137 char * cmd = request;
138 while( isspace( (unsigned char) *cmd ) )
141 // Remove trailing whitespace. We know at this point that
142 // there is at least one non-whitespace character somewhere,
143 // or we would have already skipped this line. Hence we
144 // needn't check to make sure that we don't back up past
148 // The curly braces limit the scope of the end variable
150 char * end = cmd + strlen(cmd) - 1;
151 while( isspace( (unsigned char) *end ) )
156 if( !strcasecmp(cmd, "exit") || !strcasecmp(cmd, "quit"))
162 char* req_copy = strdup(cmd);
164 parse_request( req_copy );
165 if( request && *cmd ) {
166 add_history(request);
176 if( newline_needed ) {
178 // We left the readline loop after seeing an EOF, not after
179 // seeing "quit" or "exit". So we issue a newline in order
180 // to avoid leaving a dangling prompt.
185 if(history_file != NULL )
186 write_history(history_file);
192 if( osrfHashGetCount( server_hash ) > 0 )
193 close_all_sessions();
194 osrfHashFree( server_hash );
197 osrf_system_shutdown();
201 // Get a logical line from one or more calls to readline(),
202 // skipping blank lines and comments. Stitch continuation
203 // lines together as needed. Caller is responsible for
204 // freeing the string returned.
205 // If EOF appears before a logical line is completed,
207 static char* get_request( void ) {
211 // Get the first physical line of the logical line
213 line = readline( prompt );
215 return NULL; // end of file
217 // Skip leading white space
218 for( p = line; isspace( *p ); ++p )
221 if( '\\' == *p && '\0' == p[1] ) {
222 // Just a trailing backslash; skip to next line
225 } else if( '\0' == p[0] || '#' == *p ) {
227 continue; // blank line or comment; skip it
229 break; // Not blank, not comment; take it
232 char* end = line + strlen( line ) - 1;
234 return line; // No continuation line; we're done
236 // Remove the trailing backslash and collect
237 // the continuation line(s) into a growing_buffer
240 growing_buffer* logical_line = buffer_init( 256 );
241 buffer_add( logical_line, p );
244 // Append any continuation lines
245 int finished = 0; // boolean
247 line = readline( "> " );
250 // Check for another continuation
251 end = line + strlen( line ) - 1;
257 buffer_add( logical_line, line );
260 fprintf( stderr, "Expected continuation line; found end of file\n" );
261 buffer_free( logical_line );
266 return buffer_release( logical_line );
269 static int load_history( void ) {
271 char* home = getenv("HOME");
272 int l = strlen(home) + 24;
274 snprintf(fbuf, sizeof(fbuf), "%s/.srfsh_history", home);
275 history_file = strdup(fbuf);
277 if(!access(history_file, W_OK | R_OK )) {
278 history_length = 5000;
279 read_history(history_file);
285 static int parse_error( char* words[] ) {
289 growing_buffer * gbuf = buffer_init( 64 );
290 buffer_add( gbuf, *words );
292 buffer_add( gbuf, " " );
293 buffer_add( gbuf, *words );
295 fprintf( stderr, "???: %s\n", gbuf->buf );
303 static int parse_request( char* request ) {
305 if( request == NULL )
308 char* original_request = strdup( request );
309 char* words[COMMAND_BUFSIZE];
316 char* cur_tok = strtok( req, " \t" );
318 if( cur_tok == NULL )
320 free( original_request );
324 /* Load an array with pointers to */
325 /* the tokens as defined by strtok() */
327 while(cur_tok != NULL) {
328 if( i < COMMAND_BUFSIZE - 1 ) {
329 words[i++] = cur_tok;
330 cur_tok = strtok( NULL, " \t" );
332 fprintf( stderr, "Too many tokens in command\n" );
333 free( original_request );
340 /* pass off to the top level command */
341 if( !strcmp(words[0],"router") )
342 ret_val = handle_router( words );
344 else if( !strcmp(words[0],"time") )
345 ret_val = handle_time( words );
347 else if (!strcmp(words[0],"request"))
348 ret_val = handle_request( words, 0 );
350 else if (!strcmp(words[0],"relay"))
351 ret_val = handle_request( words, 1 );
353 else if (!strcmp(words[0],"help"))
354 ret_val = print_help();
356 else if (!strcmp(words[0],"set"))
357 ret_val = handle_set(words);
359 else if (!strcmp(words[0],"print"))
360 ret_val = handle_print(words);
362 else if (!strcmp(words[0],"math_bench"))
363 ret_val = handle_math(words);
365 else if (!strcmp(words[0],"introspect"))
366 ret_val = handle_introspect(words);
368 else if (!strcmp(words[0],"login"))
369 ret_val = handle_login(words);
371 else if (!strcmp(words[0],"open"))
372 ret_val = handle_open(words);
374 else if (!strcmp(words[0],"close"))
375 ret_val = handle_close(words);
377 else if (words[0][0] == '!') {
378 system( original_request + 1 );
382 free( original_request );
385 return parse_error( words );
391 static int handle_introspect(char* words[]) {
396 fprintf(stderr, "--> %s\n", words[1]);
398 // Build a command in a suitably-sized
399 // buffer and then parse it
403 static const char text[] = "request %s opensrf.system.method %s";
404 len = sizeof( text ) + strlen( words[1] ) + strlen( words[2] );
406 snprintf( buf, sizeof(buf), text, words[1], words[2] );
407 return parse_request( buf );
410 static const char text[] = "request %s opensrf.system.method.all";
411 len = sizeof( text ) + strlen( words[1] );
413 snprintf( buf, sizeof(buf), text, words[1] );
414 return parse_request( buf );
420 static int handle_login( char* words[]) {
422 if( words[1] && words[2]) {
424 char* username = words[1];
425 char* password = words[2];
426 char* type = words[3];
427 char* orgloc = words[4];
428 char* workstation = words[5];
429 int orgloci = (orgloc) ? atoi(orgloc) : 0;
430 if(!type) type = "opac";
432 char login_text[] = "request open-ils.auth open-ils.auth.authenticate.init \"%s\"";
433 size_t len = sizeof( login_text ) + strlen(username) + 1;
436 snprintf( buf, sizeof(buf), login_text, username );
440 if(last_result && last_result->_result_content) {
441 jsonObject* r = last_result->_result_content;
442 hash = jsonObjectGetString(r);
446 char* pass_buf = md5sum(password);
448 size_t both_len = strlen( hash ) + strlen( pass_buf ) + 1;
449 char both_buf[both_len];
450 snprintf(both_buf, sizeof(both_buf), "%s%s", hash, pass_buf);
452 char* mess_buf = md5sum(both_buf);
454 growing_buffer* argbuf = buffer_init(64);
456 "request open-ils.auth open-ils.auth.authenticate.complete "
457 "{ \"username\" : \"%s\", \"password\" : \"%s\"", username, mess_buf );
459 if(type) buffer_fadd( argbuf, ", \"type\" : \"%s\"", type );
460 if(orgloci) buffer_fadd( argbuf, ", \"org\" : %d", orgloci );
461 if(workstation) buffer_fadd( argbuf, ", \"workstation\" : \"%s\"", workstation);
462 buffer_add(argbuf, "}");
467 parse_request( argbuf->buf );
470 if( login_session != NULL )
471 free( login_session );
473 const jsonObject* x = last_result->_result_content;
476 const char* authtoken = jsonObjectGetString(
477 jsonObjectGetKeyConst(jsonObjectGetKeyConst(x,"payload"), "authtoken"));
478 authtime = jsonObjectGetNumber(
479 jsonObjectGetKeyConst(jsonObjectGetKeyConst(x,"payload"), "authtime"));
482 login_session = strdup(authtoken);
484 login_session = NULL;
486 else login_session = NULL;
488 printf("Login Session: %s. Session timeout: %f\n",
489 (login_session ? login_session : "(none)"), authtime );
499 * Open connections to one or more specified services
501 static int handle_open( char* words[]) {
502 if( NULL == words[ 1 ] ) {
503 if( ! server_hash || osrfHashGetCount( server_hash ) == 0 ) {
504 printf( "No services are currently open\n" );
508 printf( "Service(s) currently open:\n" );
510 osrfHashIterator* itr = osrfNewHashIterator( server_hash );
511 while( osrfHashIteratorNext( itr ) ) {
512 printf( "\t%s\n", osrfHashIteratorKey( itr ) );
514 osrfHashIteratorFree( itr );
519 server_hash = osrfNewHash( 6 );
522 for( i = 1; words[ i ]; ++i ) { // for each requested service
523 const char* server = words[ i ];
524 if( osrfHashGet( server_hash, server ) ) {
525 printf( "Service %s is already open\n", server );
529 // Try to open a session with the current specified server
530 osrfAppSession* session = osrfAppSessionClientInit(server);
532 if(!osrfAppSessionConnect(session)) {
533 fprintf(stderr, "Unable to open service %s\n", server);
534 osrfLogWarning( OSRF_LOG_MARK, "Unable to open remote service %s\n", server );
535 osrfAppSessionFree( session );
537 osrfHashSet( server_hash, session, server );
538 printf( "Service %s opened\n", server );
546 * Close connections to one or more specified services
548 static int handle_close( char* words[]) {
549 if( NULL == words[ 1 ] ) {
550 fprintf( stderr, "No service specified for close\n" );
555 for( i = 1; words[ i ]; ++i ) {
556 const char* server = words[ i ];
558 osrfAppSession* session = osrfHashRemove( server_hash, server );
560 printf( "Service \"%s\" is not open\n", server );
564 osrf_app_session_disconnect( session );
565 osrfAppSessionFree( session );
566 printf( "Service \"%s\" closed\n", server );
573 * Close all currently open connections to services
575 static void close_all_sessions( void ) {
577 osrfAppSession* session;
578 osrfHashIterator* itr = osrfNewHashIterator( server_hash );
580 while(( session = osrfHashIteratorNext( itr ) )) {
581 osrf_app_session_disconnect( session );
582 osrfAppSessionFree( session );
585 osrfHashIteratorFree( itr );
588 static int handle_set( char* words[]) {
591 if( (variable=words[1]) ) {
594 if( (val=words[2]) ) {
596 if(!strcmp(variable,"pretty_print")) {
597 if(!strcmp(val,"true")) {
599 printf("pretty_print = true\n");
602 if(!strcmp(val,"false")) {
604 printf("pretty_print = false\n");
609 if(!strcmp(variable,"raw_print")) {
610 if(!strcmp(val,"true")) {
612 printf("raw_print = true\n");
615 if(!strcmp(val,"false")) {
617 printf("raw_print = false\n");
629 static int handle_print( char* words[]) {
632 if( (variable=words[1]) ) {
633 if(!strcmp(variable,"pretty_print")) {
635 printf("pretty_print = true\n");
638 printf("pretty_print = false\n");
643 if(!strcmp(variable,"raw_print")) {
645 printf("raw_print = true\n");
648 printf("raw_print = false\n");
653 if(!strcmp(variable,"login")) {
654 printf("login session = %s\n",
655 login_session ? login_session : "(none)" );
663 static int handle_router( char* words[] ) {
671 if( !strcmp(words[1],"query") ) {
673 if( words[2] && !strcmp(words[2],"servers") ) {
674 for(i=3; i < COMMAND_BUFSIZE - 3 && words[i]; i++ ) {
675 router_query_servers( words[i] );
688 static int handle_request( char* words[], int relay ) {
694 char* server = words[1];
695 char* method = words[2];
697 growing_buffer* buffer = NULL;
699 buffer = buffer_init(128);
700 buffer_add(buffer, "[");
701 for(i = 3; words[i] != NULL; i++ ) {
702 /* removes trailing semicolon if user accidentally enters it */
703 if( words[i][strlen(words[i])-1] == ';' )
704 words[i][strlen(words[i])-1] = '\0';
705 buffer_add( buffer, words[i] );
706 buffer_add(buffer, " ");
708 buffer_add(buffer, "]");
711 int rc = send_request( server, method, buffer, relay );
712 buffer_free( buffer );
719 int send_request( char* server,
720 char* method, growing_buffer* buffer, int relay ) {
721 if( server == NULL || method == NULL )
724 jsonObject* params = NULL;
726 if( buffer != NULL && buffer->n_used > 0 )
727 params = jsonParseString(buffer->buf);
729 if(!last_result || ! last_result->_result_content) {
730 printf("We're not going to call 'relay' with no result params\n");
734 params = jsonNewObject(NULL);
735 jsonObjectPush(params, last_result->_result_content );
739 if(buffer->n_used > 0 && params == NULL) {
740 fprintf(stderr, "JSON error detected, not executing\n");
741 jsonObjectFree(params);
745 int session_is_temporary; // boolean
746 osrfAppSession* session = osrfHashGet( server_hash, server );
748 session_is_temporary = 0; // use an existing session
750 session = osrfAppSessionClientInit(server); // open a session
751 session_is_temporary = 1; // just for this request
754 if(!osrfAppSessionConnect(session)) {
755 fprintf(stderr, "Unable to communicate with service %s\n", server);
756 osrfLogWarning( OSRF_LOG_MARK, "Unable to connect to remote service %s\n", server );
757 osrfAppSessionFree( session );
758 jsonObjectFree(params);
762 double start = get_timestamp_millis();
764 int req_id = osrfAppSessionMakeRequest( session, params, method, 1, NULL );
765 jsonObjectFree(params);
767 osrfMessage* omsg = osrfAppSessionRequestRecv( session, req_id, recv_timeout );
770 printf("\nReceived no data from server\n");
773 signal(SIGPIPE, SIG_IGN);
776 if(!is_from_script) less = popen( "less -EX", "w");
779 if( less == NULL ) { less = stdout; }
781 growing_buffer* resp_buffer = buffer_init(4096);
787 if(omsg->_result_content) {
789 osrfMessageFree(last_result);
795 char* j = jsonObjectToJSON(omsg->_result_content);
796 //content = json_printer(j);
797 content = jsonFormatString(j);
800 const char * temp_content = jsonObjectGetString(omsg->_result_content);
802 temp_content = "[null]";
803 content = strdup( temp_content );
806 printf( "\nReceived Data: %s\n", content );
812 snprintf( code, sizeof(code), "%d", omsg->status_code );
813 buffer_add( resp_buffer, code );
815 printf( "\nReceived Exception:\nName: %s\nStatus: %s\nStatus: %s\n",
816 omsg->status_name, omsg->status_text, code );
819 osrfMessageFree(omsg);
824 if(omsg->_result_content) {
826 osrfMessageFree(last_result);
831 if( pretty_print && omsg->_result_content ) {
832 char* j = jsonObjectToJSON(omsg->_result_content);
833 //content = json_printer(j);
834 content = jsonFormatString(j);
837 const char * temp_content = jsonObjectGetString(omsg->_result_content);
839 content = strdup( temp_content );
844 buffer_add( resp_buffer, "\nReceived Data: " );
845 buffer_add( resp_buffer, content );
846 buffer_add( resp_buffer, "\n" );
851 buffer_add( resp_buffer, "\nReceived Exception:\nName: " );
852 buffer_add( resp_buffer, omsg->status_name );
853 buffer_add( resp_buffer, "\nStatus: " );
854 buffer_add( resp_buffer, omsg->status_text );
855 buffer_add( resp_buffer, "\nStatus: " );
857 snprintf( code, sizeof(code), "%d", omsg->status_code );
858 buffer_add( resp_buffer, code );
859 osrfMessageFree(omsg);
863 omsg = osrfAppSessionRequestRecv( session, req_id, recv_timeout );
867 double end = get_timestamp_millis();
869 fputs( resp_buffer->buf, less );
870 buffer_free( resp_buffer );
871 fputs("\n------------------------------------\n", less);
872 if( osrf_app_session_request_complete( session, req_id ))
873 fputs("Request Completed Successfully\n", less);
876 fprintf(less, "Request Time in seconds: %.6f\n", end - start );
877 fputs("------------------------------------\n", less);
881 osrf_app_session_request_finish( session, req_id );
883 if( session_is_temporary ) {
884 osrf_app_session_disconnect( session );
885 osrfAppSessionFree( session );
893 static int handle_time( char* words[] ) {
895 printf("%f\n", get_timestamp_millis());
897 time_t epoch = (time_t) atoi(words[1]);
898 printf("%s", ctime(&epoch));
905 static int router_query_servers( const char* router_server ) {
907 if( ! router_server || strlen(router_server) == 0 )
910 const static char router_text[] = "router@%s/router";
911 size_t len = sizeof( router_text ) + strlen( router_server ) + 1;
913 snprintf(rbuf, sizeof(rbuf), router_text, router_server );
915 transport_message* send =
916 message_init( "servers", NULL, NULL, rbuf, NULL );
917 message_set_router_info( send, NULL, NULL, NULL, "query", 0 );
919 client_send_message( client, send );
920 message_free( send );
922 transport_message* recv = client_recv( client, -1 );
924 fprintf(stderr, "NULL message received from router\n");
929 "---------------------------------------------------------------------------------\n"
930 "Received from 'server' query on %s\n"
931 "---------------------------------------------------------------------------------\n"
932 "original reg time | latest reg time | last used time | class | server\n"
933 "---------------------------------------------------------------------------------\n"
935 "---------------------------------------------------------------------------------\n"
936 , router_server, recv->body );
938 message_free( recv );
943 static int print_help( void ) {
946 "---------------------------------------------------------------------------------\n"
948 "---------------------------------------------------------------------------------\n"
949 "help - Display this message\n"
950 "!<command> [args] - Forks and runs the given command in the shell\n"
952 "time - Prints the current time\n"
953 "time <timestamp> - Formats seconds since epoch into readable format\n"
955 "set <variable> <value> - set a srfsh variable (e.g. set pretty_print true )\n"
956 "print <variable> - Displays the value of a srfsh variable\n"
957 "---------------------------------------------------------------------------------\n"
959 "router query servers <server1 [, server2, ...]>\n"
960 " - Returns stats on connected services\n"
963 "request <service> <method> [ <json formatted string of params> ]\n"
964 " - Anything passed in will be wrapped in a json array,\n"
965 " so add commas if there is more than one param\n"
968 "relay <service> <method>\n"
969 " - Performs the requested query using the last received result as the param\n"
972 "math_bench <num_batches> [0|1|2]\n"
973 " - 0 means don't reconnect, 1 means reconnect after each batch of 4, and\n"
974 " 2 means reconnect after every request\n"
976 "introspect <service>\n"
977 " - prints the API for the service\n"
980 "---------------------------------------------------------------------------------\n"
981 " Commands for Open-ILS\n"
982 "---------------------------------------------------------------------------------\n"
983 "login <username> <password> [type] [org_unit] [workstation]\n"
984 " - Logs into the 'server' and displays the session id\n"
985 " - To view the session id later, enter: print login\n"
986 "---------------------------------------------------------------------------------\n"
989 "Note: long output is piped through 'less'. To search in 'less', type: /<search>\n"
990 "---------------------------------------------------------------------------------\n"
999 static char* tabs(int count) {
1000 growing_buffer* buf = buffer_init(24);
1002 for(i=0;i!=count;i++)
1003 buffer_add(buf, " ");
1005 char* final = buffer_data( buf );
1012 static int handle_math( char* words[] ) {
1014 return do_math( atoi(words[1]), 0 );
1019 static int do_math( int count, int style ) {
1021 osrfAppSession* session = osrfAppSessionClientInit( "opensrf.math" );
1022 osrfAppSessionConnect(session);
1024 jsonObject* params = jsonNewObjectType( JSON_ARRAY );
1025 jsonObjectPush(params,jsonNewObject("1"));
1026 jsonObjectPush(params,jsonNewObject("2"));
1028 char* methods[] = { "add", "sub", "mult", "div" };
1029 char* answers[] = { "3", "-1", "2", "0.5" };
1031 float times[ count * 4 ];
1032 memset(times, 0, sizeof(times));
1035 for(k=0;k!=100;k++) {
1037 fprintf(stderr,"|");
1039 fprintf(stderr,".");
1042 fprintf(stderr,"\n\n");
1046 for(i=0; i!= count; i++) {
1049 for(j=0; j != 4; j++) {
1053 double start = get_timestamp_millis();
1054 int req_id = osrfAppSessionMakeRequest( session, params, methods[j], 1, NULL );
1055 osrfMessage* omsg = osrfAppSessionRequestRecv( session, req_id, 5 );
1056 double end = get_timestamp_millis();
1058 times[(4*i) + j] = end - start;
1062 if(omsg->_result_content) {
1063 char* jsn = jsonObjectToJSON(omsg->_result_content);
1064 if(!strcmp(jsn, answers[j]))
1065 fprintf(stderr, "+");
1067 fprintf(stderr, "\n![%s] - should be %s\n", jsn, answers[j] );
1072 osrfMessageFree(omsg);
1074 } else { fprintf( stderr, "\nempty message for tt: %d\n", req_id ); }
1076 osrf_app_session_request_finish( session, req_id );
1079 osrf_app_session_disconnect( session );
1082 fprintf(stderr,"\n");
1086 osrf_app_session_disconnect( session );
1089 osrfAppSessionFree( session );
1090 jsonObjectFree(params);
1094 for(c=0; c!= count*4; c++)
1097 float avg = total / (count*4);
1098 fprintf(stderr, "\n Average round trip time: %f\n", avg );