3 int recv_timeout = 120;
4 int is_from_script = 0;
5 FILE* shell_writer = NULL;
6 FILE* shell_reader = NULL;
8 int main( int argc, char* argv[] ) {
10 /* --------------------------------------------- */
11 /* see if they have a .srfsh.xml in their home directory */
12 char* home = getenv("HOME");
13 int l = strlen(home) + 36;
16 sprintf(fbuf,"%s/.srfsh.xml",home);
18 if(!access(fbuf, R_OK)) {
19 if( ! osrf_system_bootstrap_client(fbuf, "srfsh") ) {
20 fprintf(stderr,"Unable to bootstrap client for requests\n");
21 osrfLogError( OSRF_LOG_MARK, "Unable to bootstrap client for requests");
26 fprintf(stderr,"No Config file found at %s\n", fbuf );
31 /* for now.. the first arg is used as a script file for processing */
33 if( (f = open(argv[1], O_RDONLY)) == -1 ) {
34 osrfLogError( OSRF_LOG_MARK, "Unable to open file %s for reading, exiting...", argv[1]);
38 if(dup2(f, STDIN_FILENO) == -1) {
39 osrfLogError( OSRF_LOG_MARK, "Unable to duplicate STDIN, exiting...");
47 /* --------------------------------------------- */
51 client = osrf_system_get_transport_client();
53 /* open the shell handle */
54 shell_writer = popen( "bash", "w");
55 //shell_reader = popen( "bash", "r");
57 /* main process loop */
59 while((request=readline(prompt))) {
61 if( !strcasecmp(request, "exit") || !strcasecmp(request,"quit"))
64 char* req_copy = strdup(request);
66 parse_request( req_copy );
67 if( request && strlen(request) > 1 ) {
79 if(history_file != NULL )
80 write_history(history_file);
84 osrf_system_shutdown();
88 void sig_child_handler( int s ) {
93 void sig_int_handler( int s ) {
96 signal(SIGINT,sig_int_handler);
102 char* home = getenv("HOME");
103 int l = strlen(home) + 24;
107 sprintf(fbuf,"%s/.srfsh_history",home);
108 history_file = strdup(fbuf);
110 if(!access(history_file, W_OK | R_OK )) {
111 history_length = 999;
112 read_history(history_file);
118 int parse_error( char* words[] ) {
127 memset(buffer, 0, 256);
128 while( (current=words[i++]) ) {
129 strcat(buffer, current);
132 if( ! buffer || strlen(buffer) < 1 )
135 fprintf( stderr, "???: %s\n", buffer );
141 int parse_request( char* request ) {
143 if( request == NULL )
148 char* words[COMMAND_BUFSIZE];
149 memset(words,0,COMMAND_BUFSIZE);
152 char* cur_tok = strtok( req, " " );
154 if( cur_tok == NULL )
157 while(cur_tok != NULL) {
158 words[i++] = cur_tok;
159 cur_tok = strtok( NULL, " " );
163 // not sure why (strtok?), but this is necessary
164 memset( words + i, 0, COMMAND_BUFSIZE - i );
166 /* pass off to the top level command */
167 if( !strcmp(words[0],"router") )
168 ret_val = handle_router( words );
171 else if( !strcmp(words[0],"time") )
172 ret_val = handle_time( words );
175 else if (!strcmp(words[0],"request"))
176 ret_val = handle_request( words, 0 );
178 else if (!strcmp(words[0],"relay"))
179 ret_val = handle_request( words, 1 );
181 else if (!strcmp(words[0],"help"))
182 ret_val = print_help();
184 else if (!strcmp(words[0],"set"))
185 ret_val = handle_set(words);
187 else if (!strcmp(words[0],"print"))
188 ret_val = handle_print(words);
190 else if (!strcmp(words[0],"math_bench"))
191 ret_val = handle_math(words);
193 else if (!strcmp(words[0],"introspect"))
194 ret_val = handle_introspect(words);
196 else if (!strcmp(words[0],"login"))
197 ret_val = handle_login(words);
199 else if (words[0][0] == '!')
200 ret_val = handle_exec( words, 1 );
204 return handle_exec( words, 0 );
206 return parse_error( words );
215 int handle_introspect(char* words[]) {
217 if(words[1] && words[2]) {
218 fprintf(stderr, "--> %s\n", words[1]);
221 sprintf( buf, "request %s opensrf.system.method %s", words[1], words[2] );
222 return parse_request( buf );
227 fprintf(stderr, "--> %s\n", words[1]);
230 sprintf( buf, "request %s opensrf.system.method.all", words[1] );
231 return parse_request( buf );
239 int handle_login( char* words[]) {
241 if( words[1] && words[2]) {
243 char* username = words[1];
244 char* password = words[2];
245 char* type = words[3];
246 char* orgloc = words[4];
247 char* workstation = words[5];
248 int orgloci = (orgloc) ? atoi(orgloc) : 0;
249 if(!type) type = "opac";
258 "request open-ils.auth open-ils.auth.authenticate.init \"%s\"", username );
262 if(last_result && last_result->_result_content) {
263 jsonObject* r = last_result->_result_content;
264 hash = jsonObjectGetString(r);
268 char* pass_buf = md5sum(password);
271 memset(both_buf,0,256);
272 sprintf(both_buf,"%s%s",hash, pass_buf);
274 char* mess_buf = md5sum(both_buf);
277 sprintf( buf2, "request open-ils.auth open-ils.auth.authenticate.complete "
278 "{ \"username\" : \"%s\", \"password\" : \"%s\", "
279 "\"type\" : \"%s\", \"org\" : %d, \"workstation\": \"%s\"}",
280 username, mess_buf, type, orgloci, workstation );
283 growing_buffer* argbuf = buffer_init(64);
285 "request open-ils.auth open-ils.auth.authenticate.complete "
286 "{ \"username\" : \"%s\", \"password\" : \"%s\"", username, mess_buf );
288 if(type) buffer_fadd( argbuf, ", \"type\" : \"%s\"", type );
289 if(orgloci) buffer_fadd( argbuf, ", \"org\" : %d", orgloci );
290 if(workstation) buffer_fadd( argbuf, ", \"workstation\" : \"%s\"", workstation);
291 buffer_add(argbuf, "}");
296 parse_request( argbuf->buf );
299 jsonObject* x = last_result->_result_content;
302 char* authtoken = jsonObjectGetString(
303 jsonObjectGetKey(jsonObjectGetKey(x,"payload"), "authtoken"));
304 authtime = jsonObjectGetNumber(
305 jsonObjectGetKey(jsonObjectGetKey(x,"payload"), "authtime"));
306 if(authtoken) login_session = strdup(authtoken);
307 else login_session = NULL;
309 else login_session = NULL;
311 printf("Login Session: %s. Session timeout: %lf\n", login_session, authtime );
320 int handle_set( char* words[]) {
323 if( (variable=words[1]) ) {
326 if( (val=words[2]) ) {
328 if(!strcmp(variable,"pretty_print")) {
329 if(!strcmp(val,"true")) {
331 printf("pretty_print = true\n");
334 if(!strcmp(val,"false")) {
336 printf("pretty_print = false\n");
341 if(!strcmp(variable,"raw_print")) {
342 if(!strcmp(val,"true")) {
344 printf("raw_print = true\n");
347 if(!strcmp(val,"false")) {
349 printf("raw_print = false\n");
361 int handle_print( char* words[]) {
364 if( (variable=words[1]) ) {
365 if(!strcmp(variable,"pretty_print")) {
367 printf("pretty_print = true\n");
370 printf("pretty_print = false\n");
375 if(!strcmp(variable,"login")) {
376 printf("login session = %s\n", login_session );
384 int handle_router( char* words[] ) {
392 if( !strcmp(words[1],"query") ) {
394 if( words[2] && !strcmp(words[2],"servers") ) {
395 for(i=3; i < COMMAND_BUFSIZE - 3 && words[i]; i++ ) {
396 router_query_servers( words[i] );
408 /* if new shell, spawn a new child and subshell to do the work,
409 otherwise pipe the request to the currently open (piped) shell */
410 int handle_exec(char* words[], int new_shell) {
412 if(!words[0]) return 0;
414 if( words[0] && words[0][0] == '!') {
415 int len = strlen(words[0]);
417 memset(command,0,len);
419 int i; /* chop out the ! */
420 for( i=1; i!= len; i++) {
421 command[i-1] = words[0][i];
425 words[0] = strdup(command);
429 signal(SIGCHLD, sig_child_handler);
435 signal(SIGCHLD,sig_child_handler);
440 execvp( words[0], words );
447 growing_buffer* b = buffer_init(64);
450 buffer_fadd( b, "%s ", words[i++] );
452 buffer_add( b, "\n");
455 //int reader = dup2(STDOUT_FILENO, reader);
456 //int reader = dup(STDOUT_FILENO);
457 //close(STDOUT_FILENO);
459 fprintf( shell_writer, b->buf );
462 fflush(shell_writer);
468 read( reader, c, 4095 );
469 fprintf(stderr, "read %s", c);
470 dup2(reader, STDOUT_FILENO);
480 int handle_request( char* words[], int relay ) {
486 char* server = words[1];
487 char* method = words[2];
489 growing_buffer* buffer = NULL;
491 buffer = buffer_init(128);
492 buffer_add(buffer, "[");
493 for(i = 3; words[i] != NULL; i++ ) {
494 /* removes trailing semicolon if user accidentally enters it */
495 if( words[i][strlen(words[i])-1] == ';' )
496 words[i][strlen(words[i])-1] = '\0';
497 buffer_add( buffer, words[i] );
498 buffer_add(buffer, " ");
500 buffer_add(buffer, "]");
503 return send_request( server, method, buffer, relay );
509 int send_request( char* server,
510 char* method, growing_buffer* buffer, int relay ) {
511 if( server == NULL || method == NULL )
514 jsonObject* params = NULL;
516 if( buffer != NULL && buffer->n_used > 0 )
517 params = json_parse_string(buffer->buf);
519 if(!last_result || ! last_result->_result_content) {
520 printf("We're not going to call 'relay' with no result params\n");
524 jsonObject* o = jsonNewObject(NULL);
525 jsonObjectPush(o, last_result->_result_content );
531 if(buffer->n_used > 0 && params == NULL) {
532 fprintf(stderr, "JSON error detected, not executing\n");
536 osrf_app_session* session = osrf_app_client_session_init(server);
538 if(!osrf_app_session_connect(session)) {
539 osrfLogWarning( OSRF_LOG_MARK, "Unable to connect to remote service %s\n", server );
543 double start = get_timestamp_millis();
544 //int req_id = osrf_app_session_make_request( session, params, method, 1, NULL );
545 int req_id = osrf_app_session_make_req( session, params, method, 1, NULL );
548 osrf_message* omsg = osrf_app_session_request_recv( session, req_id, recv_timeout );
551 printf("\nReceived no data from server\n");
554 signal(SIGPIPE, SIG_IGN);
557 if(!is_from_script) less = popen( "less -EX", "w");
560 if( less == NULL ) { less = stdout; }
562 growing_buffer* resp_buffer = buffer_init(4096);
568 if(omsg->_result_content) {
570 osrf_message_free(last_result);
575 if( pretty_print && omsg->_result_content ) {
576 char* j = jsonObjectToJSON(omsg->_result_content);
577 //content = json_printer(j);
578 content = jsonFormatString(j);
581 content = jsonObjectGetString(omsg->_result_content);
583 printf( "\nReceived Data: %s\n", content );
590 sprintf( code, "%d", omsg->status_code );
591 buffer_add( resp_buffer, code );
593 printf( "\nReceived Exception:\nName: %s\nStatus: %s\nStatus: %s\n",
594 omsg->status_name, omsg->status_text, code );
601 if(omsg->_result_content) {
603 osrf_message_free(last_result);
608 if( pretty_print && omsg->_result_content ) {
609 char* j = jsonObjectToJSON(omsg->_result_content);
610 //content = json_printer(j);
611 content = jsonFormatString(j);
614 content = jsonObjectGetString(omsg->_result_content);
616 buffer_add( resp_buffer, "\nReceived Data: " );
617 buffer_add( resp_buffer, content );
618 buffer_add( resp_buffer, "\n" );
623 buffer_add( resp_buffer, "\nReceived Exception:\nName: " );
624 buffer_add( resp_buffer, omsg->status_name );
625 buffer_add( resp_buffer, "\nStatus: " );
626 buffer_add( resp_buffer, omsg->status_text );
627 buffer_add( resp_buffer, "\nStatus: " );
630 sprintf( code, "%d", omsg->status_code );
631 buffer_add( resp_buffer, code );
636 omsg = osrf_app_session_request_recv( session, req_id, recv_timeout );
640 double end = get_timestamp_millis();
642 fprintf( less, resp_buffer->buf );
643 buffer_free( resp_buffer );
644 fprintf( less, "\n------------------------------------\n");
645 if( osrf_app_session_request_complete( session, req_id ))
646 fprintf(less, "Request Completed Successfully\n");
649 fprintf(less, "Request Time in seconds: %.6f\n", end - start );
650 fprintf(less, "------------------------------------\n");
654 osrf_app_session_request_finish( session, req_id );
655 osrf_app_session_disconnect( session );
656 osrf_app_session_destroy( session );
665 int handle_time( char* words[] ) {
672 printf( "%s\n", buf );
677 time_t epoch = (time_t)atoi( words[1] );
678 char* localtime = strdup( ctime( &epoch ) );
679 printf( "%s => %s", words[1], localtime );
691 int router_query_servers( char* router_server ) {
693 if( ! router_server || strlen(router_server) == 0 )
698 sprintf(rbuf,"router@%s/router", router_server );
700 transport_message* send =
701 message_init( "servers", NULL, NULL, rbuf, NULL );
702 message_set_router_info( send, NULL, NULL, NULL, "query", 0 );
704 client_send_message( client, send );
705 message_free( send );
707 transport_message* recv = client_recv( client, -1 );
709 fprintf(stderr, "NULL message received from router\n");
714 "---------------------------------------------------------------------------------\n"
715 "Received from 'server' query on %s\n"
716 "---------------------------------------------------------------------------------\n"
717 "original reg time | latest reg time | last used time | class | server\n"
718 "---------------------------------------------------------------------------------\n"
720 "---------------------------------------------------------------------------------\n"
721 , router_server, recv->body );
723 message_free( recv );
731 "---------------------------------------------------------------------------------\n"
733 "---------------------------------------------------------------------------------\n"
734 "help - Display this message\n"
735 "!<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"
738 "set <variable> <value> - set a srfsh variable (e.g. set pretty_print true )\n"
739 "print <variable> - Displays the value of a srfsh variable\n"
740 "---------------------------------------------------------------------------------\n"
742 "router query servers <server1 [, server2, ...]>\n"
743 " - Returns stats on connected services\n"
746 "request <service> <method> [ <json formatted string of params> ]\n"
747 " - Anything passed in will be wrapped in a json array,\n"
748 " so add commas if there is more than one param\n"
751 "relay <service> <method>\n"
752 " - Performs the requested query using the last received result as the param\n"
755 "math_bench <num_batches> [0|1|2]\n"
756 " - 0 means don't reconnect, 1 means reconnect after each batch of 4, and\n"
757 " 2 means reconnect after every request\n"
759 "introspect <service>\n"
760 " - prints the API for the service\n"
763 "---------------------------------------------------------------------------------\n"
764 " Commands for Open-ILS\n"
765 "---------------------------------------------------------------------------------\n"
766 "login <username> <password>\n"
767 " - Logs into the 'server' and displays the session id\n"
768 " - To view the session id later, enter: print login\n"
769 "---------------------------------------------------------------------------------\n"
772 "Note: long output is piped through 'less'. To search in 'less', type: /<search>\n"
773 "---------------------------------------------------------------------------------\n"
782 char* tabs(int count) {
783 growing_buffer* buf = buffer_init(24);
785 for(i=0;i!=count;i++)
786 buffer_add(buf, " ");
788 char* final = buffer_data( buf );
793 int handle_math( char* words[] ) {
795 return do_math( atoi(words[1]), 0 );
800 int do_math( int count, int style ) {
802 osrf_app_session* session = osrf_app_client_session_init( "opensrf.math" );
804 jsonObject* params = json_parse_string("[]");
805 jsonObjectPush(params,jsonNewObject("1"));
806 jsonObjectPush(params,jsonNewObject("2"));
808 char* methods[] = { "add", "sub", "mult", "div" };
809 char* answers[] = { "3", "-1", "2", "0.500000" };
811 float times[ count * 4 ];
812 memset(times,0,count*4);
815 for(k=0;k!=100;k++) {
822 fprintf(stderr,"\n\n");
826 for(i=0; i!= count; i++) {
829 for(j=0; j != 4; j++) {
833 double start = get_timestamp_millis();
834 int req_id = osrf_app_session_make_req( session, params, methods[j], 1, NULL );
835 osrf_message* omsg = osrf_app_session_request_recv( session, req_id, 5 );
836 double end = get_timestamp_millis();
838 times[(4*i) + j] = end - start;
842 if(omsg->_result_content) {
843 char* jsn = jsonObjectToJSON(omsg->_result_content);
844 if(!strcmp(jsn, answers[j]))
845 fprintf(stderr, "+");
847 fprintf(stderr, "\n![%s] - should be %s\n", jsn, answers[j] );
852 osrf_message_free(omsg);
854 } else { fprintf( stderr, "\nempty message for tt: %d\n", req_id ); }
856 osrf_app_session_request_finish( session, req_id );
859 osrf_app_session_disconnect( session );
862 fprintf(stderr,"\n");
866 osrf_app_session_disconnect( session );
869 osrf_app_session_destroy( session );
870 jsonObjectFree(params);
874 for(c=0; c!= count*4; c++)
877 float avg = total / (count*4);
878 fprintf(stderr, "\n Average round trip time: %f\n", avg );