1 package OpenSRF::Application;
3 use vars qw/$_app $log @_METHODS $thunk $server_class/;
6 use OpenSRF::AppSession;
7 use OpenSRF::DomainObject::oilsMethod;
8 use OpenSRF::DomainObject::oilsResponse qw/:status/;
9 use OpenSRF::Utils::Logger qw/:level $logger/;
11 use Time::HiRes qw/time/;
12 use OpenSRF::EX qw/:try/;
14 use OpenSRF::Utils::JSON;
21 $log = 'OpenSRF::Utils::Logger';
24 our @pending_requests;
29 return 1 unless ref($self);
30 return $self->{package};
35 return 0 unless ref($self);
36 return $self->{signature};
41 return 0 unless ref($self);
42 return $self->{strict};
47 return 0 unless ref($self);
53 return 0 unless ref($self);
54 return $self->{max_chunk_size} if (defined($self->{max_chunk_size}));
60 return 0 unless ref($self);
61 return $self->{max_chunk_count} || 0;
66 return 1 unless ref($self);
67 return $self->{api_name};
72 return 1 unless ref($self);
73 return $self->{api_level};
81 $self->{session} = $session;
83 return $self->{session};
89 $server_class = $class;
97 $thunk = $flag if (defined $flag);
101 sub application_implementation {
109 $log->error( "Error loading application_implementation: $app -> $@", ERROR);
118 my ($self, $session, $app_msg) = @_;
124 my $app = $self->application_implementation;
126 if ($session->last_message_type eq 'REQUEST') {
128 my @p = $app_msg->params;
129 my $method_name = $app_msg->method;
130 my $method_proto = $session->last_message_api_level;
132 # By default, we log all method params at the info level
133 # Here we are consult our shared portion of the config file
134 # to look for any exceptions to this behavior
135 my $logdata = "CALL: ".$session->service." $method_name ";
136 my $redact_params = 0;
138 if (ref($shared_conf->shared->log_protect) eq 'ARRAY') {
139 foreach my $match_string (@{$shared_conf->shared->log_protect}) {
140 if ($method_name =~ /^$match_string/) {
146 if ($redact_params) {
147 $logdata .= "**PARAMS REDACTED**";
149 $logdata .= join(', ', map { (defined $_) ? $_ : '' } @p);
152 $log->info($logdata);
154 my $coderef = $app->method_lookup( $method_name, $method_proto, 1, 1 );
157 $session->status( OpenSRF::DomainObject::oilsMethodException->new(
158 statusCode => STATUS_NOTFOUND(),
159 status => "Method [$method_name] not found for $app"));
163 unless ($session->continue_request) {
165 OpenSRF::DomainObject::oilsConnectStatus->new(
166 statusCode => STATUS_REDIRECTED(),
167 status => 'Disconnect on max requests' ) );
173 my @args = $app_msg->params;
174 $coderef->session( $session );
175 my $appreq = OpenSRF::AppRequest->new( $session );
176 $appreq->max_chunk_size( $coderef->max_chunk_size );
177 $appreq->max_chunk_count( $coderef->max_chunk_count );
179 $log->debug( "in_request = $in_request : [" . $appreq->threadTrace."]", INTERNAL );
181 $log->debug( "Pushing onto pending requests: " . $appreq->threadTrace, DEBUG );
182 push @pending_requests, [ $appreq, \@args, $coderef ];
189 $log->debug( "Executing coderef for {$method_name}", INTERNAL );
193 # un-if(0) this block to enable param checking based on signature and argc
194 if ($coderef->strict) {
195 if (@args < $coderef->argc) {
196 die "Not enough params passed to ".
197 $coderef->api_name." : requires ". $coderef->argc
200 my $sig = $coderef->signature;
201 if ($sig && exists $sig->{params}) {
202 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
203 my $s = $sig->{params}->[$p];
205 if ($s->{class} && OpenSRF::Utils::JSON->lookup_hint(ref $a) ne $s->{class}) {
206 die "Incorrect param class at position $p : should be a '$$s{class}'";
207 } elsif ($s->{type}) {
208 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
209 die "Incorrect param type at position $p : should be an 'object'";
210 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
211 die "Incorrect param type at position $p : should be an 'array'";
212 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
213 die "Incorrect param type at position $p : should be a 'number'";
214 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
215 die "Incorrect param type at position $p : should be a 'string'";
224 $resp = $coderef->run( $appreq, @args);
225 my $time = sprintf '%.3f', time() - $start;
227 $log->debug( "Method duration for [$method_name]: ". $time );
228 $appreq->respond_complete( $resp );
232 warn "Caught error from 'run' method: $e\n";
234 if(UNIVERSAL::isa($e,"Error")) {
235 $e = $e->stringify();
237 my $sess_id = $session->session_id;
239 OpenSRF::DomainObject::oilsMethodException->new(
240 statusCode => STATUS_INTERNALSERVERERROR(),
241 status => " *** Call to [$method_name] failed for session ".
242 "[$sess_id], thread trace ".
243 "[".$appreq->threadTrace."]:\n$e\n"
250 # ----------------------------------------------
253 # XXX may need this later
254 # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
258 $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
260 # cycle through queued requests
261 while( my $aref = shift @pending_requests ) {
265 # un-if(0) this block to enable param checking based on signature and argc
267 if (@args < $aref->[2]->argc) {
268 die "Not enough params passed to ".
269 $aref->[2]->api_name." : requires ". $aref->[2]->argc
272 my $sig = $aref->[2]->signature;
273 if ($sig && exists $sig->{params}) {
274 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
275 my $s = $sig->{params}->[$p];
277 if ($s->{class} && OpenSRF::Utils::JSON->lookup_hint(ref $a) ne $s->{class}) {
278 die "Incorrect param class at position $p : should be a '$$s{class}'";
279 } elsif ($s->{type}) {
280 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
281 die "Incorrect param type at position $p : should be an 'object'";
282 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
283 die "Incorrect param type at position $p : should be an 'array'";
284 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
285 die "Incorrect param type at position $p : should be a 'number'";
286 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
287 die "Incorrect param type at position $p : should be a 'string'";
296 my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
297 my $time = sprintf '%.3f', time - $start;
298 $log->debug( "Method duration for [".$aref->[2]->api_name." -> ".join(', ',@{$aref->[1]}).']: '.$time, DEBUG );
300 $appreq = $aref->[0];
301 $appreq->respond_complete( $response );
302 $log->debug( "Executed: " . $appreq->threadTrace, INTERNAL );
306 if(UNIVERSAL::isa($e,"Error")) {
307 $e = $e->stringify();
310 OpenSRF::DomainObject::oilsMethodException->new(
311 statusCode => STATUS_INTERNALSERVERERROR(),
312 status => "Call to [".$aref->[2]->api_name."] faild: $e"
322 $log->info("Received non-REQUEST message in Application handler");
324 my $res = OpenSRF::DomainObject::oilsMethodException->new(
325 status => "Received non-REQUEST message in Application handler");
326 $session->send('ERROR', $res);
331 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
334 $session->last_message_type('');
335 $session->last_message_api_level('');
342 my $api_name = shift;
343 my $api_level = shift || 1;
344 return exists($_METHODS[$api_level]{$api_name});
348 sub normalize_whitespace {
355 $txt =~ s/\. /\. /gso;
360 sub parse_string_signature {
362 return [] unless $string;
363 my @chunks = split(/\@/smo, $string);
369 if (/^return (.+)$/so) {
370 $ret = [normalize_whitespace($1)];
371 } elsif (/^param (\w+) \b(.+)$/so) {
372 push @params, [ $1, normalize_whitespace($2) ];
374 $desc .= '@' if $desc;
379 return [normalize_whitespace($desc),\@params, $ret];
382 sub parse_array_signature {
384 my ($d,$p,$r) = @$array;
385 return {} unless ($d or $p or $r);
406 sub register_method {
408 my $app = ref($self) || $self;
412 throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
414 $args{api_level} = 1 unless(defined($args{api_level}));
418 $args{package} ||= $app;
419 $args{server_class} = server_class();
420 $args{api_name} ||= $args{server_class} . '.' . $args{method};
422 # un-if(0) this block to enable signature parsing
423 if (!$args{signature}) {
424 if ($args{notes} && !ref($args{notes})) {
426 parse_array_signature( parse_string_signature( $args{notes} ) );
428 } elsif( !ref($args{signature}) ) {
430 parse_array_signature( parse_string_signature( $args{signature} ) );
431 } elsif( ref($args{signature}) eq 'ARRAY') {
433 parse_array_signature( $args{signature} );
436 unless ($args{object_hint}) {
437 ($args{object_hint} = $args{package}) =~ s/::/_/go;
440 OpenSRF::Utils::JSON->register_class_hint(
441 strip => ['session'],
443 hint => $args{object_hint},
447 $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
449 __PACKAGE__->register_method(
452 api_name => $args{api_name}.'.atomic',
453 method => 'make_stream_atomic',
454 notes => "This is a system generated method. Please see the definition for $args{api_name}",
455 ) if ($args{stream});
458 sub retrieve_remote_apis {
460 my $session = OpenSRF::AppSession->create('router');
462 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
465 $log->debug( "Remote subrequest returned an error:\n". $e );
468 return undef unless ($session->state == $session->CONNECTED);
471 my $req = $session->request( 'opensrf.router.info.class.list' );
472 my $list = $req->recv;
474 if( UNIVERSAL::isa($list,"Error") ) {
478 my $content = $list->content;
482 $session->disconnect;
484 my %u_list = map { ($_ => 1) } @$content;
486 for my $class ( keys %u_list ) {
487 next if($class eq $server_class);
488 populate_remote_method_cache($class, $method);
492 sub populate_remote_method_cache {
496 my $session = OpenSRF::AppSession->create($class);
498 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
500 my $call = 'opensrf.system.method.all' unless (defined $meth);
501 $call = 'opensrf.system.method' if (defined $meth);
503 my $req = $session->request( $call, $meth );
505 while (my $method = $req->recv) {
506 next if (UNIVERSAL::isa($method, 'Error'));
508 $method = $method->content;
509 next if ( exists($_METHODS[$$method{api_level}]) &&
510 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
511 $method->{remote} = 1;
512 bless($method, __PACKAGE__ );
513 $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
518 $session->disconnect;
522 $log->debug( "Remote subrequest returned an error:\n". $e );
531 my $no_recurse = shift || 0;
532 my $no_remote = shift || 0;
534 # this instead of " || 1;" above to allow api_level 0
535 $proto = $self->api_level unless (defined $proto);
537 my $class = ref($self) || $self;
539 $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
540 $log->debug("Available methods\n\t".join("\n\t", keys %{ $_METHODS[$proto] }), INTERNAL);
543 if (__PACKAGE__->thunk) {
544 for my $p ( reverse(1 .. $proto) ) {
545 if (exists $_METHODS[$p]{$method}) {
546 $meth = $_METHODS[$p]{$method};
550 if (exists $_METHODS[$proto]{$method}) {
551 $meth = $_METHODS[$proto]{$method};
556 if($no_remote and $meth->{remote}) {
557 $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
561 } elsif (!$no_recurse) {
562 $log->debug("We didn't find [$method], asking everyone else.", DEBUG);
563 retrieve_remote_apis($method);
564 $meth = $self->method_lookup($method,$proto,1);
567 $meth->session($self->session) if $meth && ref($self); # Pass the caller's session
578 if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
579 $log->debug("Creating a SubRequest object", DEBUG);
580 unshift @params, $req;
581 $req = OpenSRF::AppSubrequest->new( session => $self->session );
583 $log->debug("This is a top level request", DEBUG);
586 if (!$self->{remote}) {
587 my $code = \&{$self->{package} . '::' . $self->{method}};
592 $warnhandler = $SIG{__WARN__};
593 $SIG{__WARN__} = sub {
594 (my $msg = shift) =~ s/\n$//;
595 $log->warn($self->{api_name} . ": $msg");
596 return 1; # prevents warning going out to stderr
599 $resp = $code->($self, $req, @params);
604 if( ref($self) eq 'HASH') {
605 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$err\n", ERROR);
608 $SIG{__WARN__} = $warnhandler;
612 if(UNIVERSAL::isa($err,"Error")) {
620 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
622 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
623 $req->respond($resp) if (defined $resp);
624 $log->debug("SubRequest object is responding with : " . join(" ",$req->responses), DEBUG);
625 return $req->responses;
627 $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
631 my $session = OpenSRF::AppSession->create($self->{server_class});
633 #$session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
634 my $remote_req = $session->request( $self->{api_name}, @params );
635 while (my $remote_resp = $remote_req->recv) {
636 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
637 if( UNIVERSAL::isa($remote_resp,"Error") ) {
640 $req->respond( $remote_resp->content );
642 $remote_req->finish();
646 $log->debug( "Remote subrequest returned an error:\n". $e );
651 $session->disconnect();
655 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
657 return $req->responses;
659 # huh? how'd we get here...
670 if ($self->api_name =~ /all$/o) {
676 my ($seen,$returned) = (0,0);
677 for my $api_level ( reverse(1 .. $#_METHODS) ) {
678 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
679 if (!$offset || $offset <= $seen) {
680 if (!$_METHODS[$api_level]{$api_name}{remote}) {
681 if (defined($method)) {
682 if ($api_name =~ $method) {
683 if (!$limit || $returned < $limit) {
684 $client->respond( $_METHODS[$api_level]{$api_name} );
689 if (!$limit || $returned < $limit) {
690 $client->respond( $_METHODS[$api_level]{$api_name} );
702 __PACKAGE__->register_method(
704 method => 'introspect',
705 api_name => 'opensrf.system.method.all',
708 desc => q/This method is used to introspect an entire OpenSRF Application/,
710 desc => q/A stream of objects describing the methods available via this OpenSRF Application/,
715 __PACKAGE__->register_method(
717 method => 'introspect',
719 api_name => 'opensrf.system.method',
722 desc => q/Use this method to get the definition of a single OpenSRF Method/,
724 { desc => q/The method to introspect/,
727 return => { desc => q/An object describing the method requested, or an error if it can't be found/,
737 $client->respond( $_ ) for (@args);
740 __PACKAGE__->register_method(
742 method => 'echo_method',
744 api_name => 'opensrf.system.echo',
746 desc => q/A test method that will echo back it's arguments in a streaming response/,
748 { desc => q/One or more arguments to echo back/ }
750 return => { desc => q/A stream of the arguments passed/ }
755 my( $self, $conn ) = @_;
758 __PACKAGE__->register_method(
759 method => 'time_method',
761 api_name => 'opensrf.system.time',
763 desc => q/Returns the current system time as epoch seconds/,
764 return => { desc => q/epoch seconds/ }
768 sub make_stream_atomic {
773 (my $m_name = $self->api_name) =~ s/\.atomic$//o;
774 my $m = $self->method_lookup($m_name);
776 $m->session( $req->session );
777 my @results = $m->run(@args);