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_bundle_size} if (defined($self->{max_bundle_size}));
58 sub max_bundle_count {
60 return 0 unless ref($self);
61 return $self->{max_bundle_count} || 0;
66 return 0 unless ref($self);
67 return $self->{max_chunk_size} if (defined($self->{max_chunk_size}));
68 return 2 * $self->max_bundle_size;
73 return 1 unless ref($self);
74 return $self->{api_name};
79 return 1 unless ref($self);
80 return $self->{api_level};
88 $self->{session} = $session;
90 return $self->{session};
96 $server_class = $class;
104 $thunk = $flag if (defined $flag);
108 sub application_implementation {
116 $log->error( "Error loading application_implementation: $app -> $@", ERROR);
125 my ($self, $session, $app_msg) = @_;
131 my $app = $self->application_implementation;
133 if ($session->last_message_type eq 'REQUEST') {
135 my @p = $app_msg->params;
136 my $method_name = $app_msg->method;
137 my $method_proto = $session->last_message_api_level;
139 # By default, we log all method params at the info level
140 # Here we are consult our shared portion of the config file
141 # to look for any exceptions to this behavior
142 my $logdata = "CALL: ".$session->service." $method_name ";
143 my $redact_params = 0;
145 if (ref($shared_conf->shared->log_protect) eq 'ARRAY') {
146 foreach my $match_string (@{$shared_conf->shared->log_protect}) {
147 if ($method_name =~ /^$match_string/) {
153 if ($redact_params) {
154 $logdata .= "**PARAMS REDACTED**";
156 $logdata .= join(', ', map { (defined $_) ? $_ : '' } @p);
159 $log->info($logdata);
161 my $coderef = $app->method_lookup( $method_name, $method_proto, 1, 1 );
164 $session->status( OpenSRF::DomainObject::oilsMethodException->new(
165 statusCode => STATUS_NOTFOUND(),
166 status => "Method [$method_name] not found for $app"));
170 unless ($session->continue_request) {
172 OpenSRF::DomainObject::oilsConnectStatus->new(
173 statusCode => STATUS_REDIRECTED(),
174 status => 'Disconnect on max requests' ) );
180 my @args = $app_msg->params;
181 $coderef->session( $session );
182 my $appreq = OpenSRF::AppRequest->new( $session );
183 $appreq->max_bundle_size( $coderef->max_bundle_size );
184 $appreq->max_bundle_count( $coderef->max_bundle_count );
186 $log->debug( "in_request = $in_request : [" . $appreq->threadTrace."]", INTERNAL );
188 $log->debug( "Pushing onto pending requests: " . $appreq->threadTrace, DEBUG );
189 push @pending_requests, [ $appreq, \@args, $coderef ];
196 $log->debug( "Executing coderef for {$method_name}", INTERNAL );
200 # un-if(0) this block to enable param checking based on signature and argc
201 if ($coderef->strict) {
202 if (@args < $coderef->argc) {
203 die "Not enough params passed to ".
204 $coderef->api_name." : requires ". $coderef->argc
207 my $sig = $coderef->signature;
208 if ($sig && exists $sig->{params}) {
209 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
210 my $s = $sig->{params}->[$p];
212 if ($s->{class} && OpenSRF::Utils::JSON->lookup_hint(ref $a) ne $s->{class}) {
213 die "Incorrect param class at position $p : should be a '$$s{class}'";
214 } elsif ($s->{type}) {
215 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
216 die "Incorrect param type at position $p : should be an 'object'";
217 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
218 die "Incorrect param type at position $p : should be an 'array'";
219 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
220 die "Incorrect param type at position $p : should be a 'number'";
221 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
222 die "Incorrect param type at position $p : should be a 'string'";
231 $resp = $coderef->run( $appreq, @args);
232 my $time = sprintf '%.3f', time() - $start;
234 $log->debug( "Method duration for [$method_name]: ". $time );
235 $appreq->respond_complete( $resp );
239 warn "Caught error from 'run' method: $e\n";
241 if(UNIVERSAL::isa($e,"Error")) {
242 $e = $e->stringify();
244 my $sess_id = $session->session_id;
246 OpenSRF::DomainObject::oilsMethodException->new(
247 statusCode => STATUS_INTERNALSERVERERROR(),
248 status => " *** Call to [$method_name] failed for session ".
249 "[$sess_id], thread trace ".
250 "[".$appreq->threadTrace."]:\n$e\n"
257 # ----------------------------------------------
260 # XXX may need this later
261 # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
265 $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
267 # cycle through queued requests
268 while( my $aref = shift @pending_requests ) {
272 # un-if(0) this block to enable param checking based on signature and argc
274 if (@args < $aref->[2]->argc) {
275 die "Not enough params passed to ".
276 $aref->[2]->api_name." : requires ". $aref->[2]->argc
279 my $sig = $aref->[2]->signature;
280 if ($sig && exists $sig->{params}) {
281 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
282 my $s = $sig->{params}->[$p];
284 if ($s->{class} && OpenSRF::Utils::JSON->lookup_hint(ref $a) ne $s->{class}) {
285 die "Incorrect param class at position $p : should be a '$$s{class}'";
286 } elsif ($s->{type}) {
287 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
288 die "Incorrect param type at position $p : should be an 'object'";
289 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
290 die "Incorrect param type at position $p : should be an 'array'";
291 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
292 die "Incorrect param type at position $p : should be a 'number'";
293 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
294 die "Incorrect param type at position $p : should be a 'string'";
303 my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
304 my $time = sprintf '%.3f', time - $start;
305 $log->debug( "Method duration for [".$aref->[2]->api_name." -> ".join(', ',@{$aref->[1]}).']: '.$time, DEBUG );
307 $appreq = $aref->[0];
308 $appreq->respond_complete( $response );
309 $log->debug( "Executed: " . $appreq->threadTrace, INTERNAL );
313 if(UNIVERSAL::isa($e,"Error")) {
314 $e = $e->stringify();
317 OpenSRF::DomainObject::oilsMethodException->new(
318 statusCode => STATUS_INTERNALSERVERERROR(),
319 status => "Call to [".$aref->[2]->api_name."] faild: $e"
329 $log->info("Received non-REQUEST message in Application handler");
331 my $res = OpenSRF::DomainObject::oilsMethodException->new(
332 status => "Received non-REQUEST message in Application handler");
333 $session->send('ERROR', $res);
338 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
341 $session->last_message_type('');
342 $session->last_message_api_level('');
349 my $api_name = shift;
350 my $api_level = shift || 1;
351 return exists($_METHODS[$api_level]{$api_name});
355 sub normalize_whitespace {
362 $txt =~ s/\. /\. /gso;
367 sub parse_string_signature {
369 return [] unless $string;
370 my @chunks = split(/\@/smo, $string);
376 if (/^return (.+)$/so) {
377 $ret = [normalize_whitespace($1)];
378 } elsif (/^param (\w+) \b(.+)$/so) {
379 push @params, [ $1, normalize_whitespace($2) ];
381 $desc .= '@' if $desc;
386 return [normalize_whitespace($desc),\@params, $ret];
389 sub parse_array_signature {
391 my ($d,$p,$r) = @$array;
392 return {} unless ($d or $p or $r);
413 sub register_method {
415 my $app = ref($self) || $self;
419 throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
421 $args{api_level} = 1 unless(defined($args{api_level}));
425 $args{package} ||= $app;
426 $args{server_class} = server_class();
427 $args{api_name} ||= $args{server_class} . '.' . $args{method};
429 # un-if(0) this block to enable signature parsing
430 if (!$args{signature}) {
431 if ($args{notes} && !ref($args{notes})) {
433 parse_array_signature( parse_string_signature( $args{notes} ) );
435 } elsif( !ref($args{signature}) ) {
437 parse_array_signature( parse_string_signature( $args{signature} ) );
438 } elsif( ref($args{signature}) eq 'ARRAY') {
440 parse_array_signature( $args{signature} );
443 unless ($args{object_hint}) {
444 ($args{object_hint} = $args{package}) =~ s/::/_/go;
447 OpenSRF::Utils::JSON->register_class_hint(
448 strip => ['session'],
450 hint => $args{object_hint},
454 $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
456 __PACKAGE__->register_method(
459 api_name => $args{api_name}.'.atomic',
460 method => 'make_stream_atomic',
461 notes => "This is a system generated method. Please see the definition for $args{api_name}",
462 ) if ($args{stream});
465 sub retrieve_remote_apis {
467 my $session = OpenSRF::AppSession->create('router');
469 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
472 $log->debug( "Remote subrequest returned an error:\n". $e );
475 return undef unless ($session->state == $session->CONNECTED);
478 my $req = $session->request( 'opensrf.router.info.class.list' );
479 my $list = $req->recv;
481 if( UNIVERSAL::isa($list,"Error") ) {
485 my $content = $list->content;
489 $session->disconnect;
491 my %u_list = map { ($_ => 1) } @$content;
493 for my $class ( keys %u_list ) {
494 next if($class eq $server_class);
495 populate_remote_method_cache($class, $method);
499 sub populate_remote_method_cache {
503 my $session = OpenSRF::AppSession->create($class);
505 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
507 my $call = 'opensrf.system.method.all' unless (defined $meth);
508 $call = 'opensrf.system.method' if (defined $meth);
510 my $req = $session->request( $call, $meth );
512 while (my $method = $req->recv) {
513 next if (UNIVERSAL::isa($method, 'Error'));
515 $method = $method->content;
516 next if ( exists($_METHODS[$$method{api_level}]) &&
517 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
518 $method->{remote} = 1;
519 bless($method, __PACKAGE__ );
520 $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
525 $session->disconnect;
529 $log->debug( "Remote subrequest returned an error:\n". $e );
538 my $no_recurse = shift || 0;
539 my $no_remote = shift || 0;
541 # this instead of " || 1;" above to allow api_level 0
542 $proto = $self->api_level unless (defined $proto);
544 my $class = ref($self) || $self;
546 $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
547 $log->debug("Available methods\n\t".join("\n\t", keys %{ $_METHODS[$proto] }), INTERNAL);
550 if (__PACKAGE__->thunk) {
551 for my $p ( reverse(1 .. $proto) ) {
552 if (exists $_METHODS[$p]{$method}) {
553 $meth = $_METHODS[$p]{$method};
557 if (exists $_METHODS[$proto]{$method}) {
558 $meth = $_METHODS[$proto]{$method};
563 if($no_remote and $meth->{remote}) {
564 $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
568 } elsif (!$no_recurse) {
569 $log->debug("We didn't find [$method], asking everyone else.", DEBUG);
570 retrieve_remote_apis($method);
571 $meth = $self->method_lookup($method,$proto,1);
574 $meth->session($self->session) if $meth && ref($self); # Pass the caller's session
585 if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
586 $log->debug("Creating a SubRequest object", DEBUG);
587 unshift @params, $req;
588 $req = OpenSRF::AppSubrequest->new( session => $self->session );
590 $log->debug("This is a top level request", DEBUG);
593 if (!$self->{remote}) {
594 my $code = \&{$self->{package} . '::' . $self->{method}};
599 $warnhandler = $SIG{__WARN__};
600 $SIG{__WARN__} = sub {
601 (my $msg = shift) =~ s/\n$//;
602 $log->warn($self->{api_name} . ": $msg");
603 return 1; # prevents warning going out to stderr
606 $resp = $code->($self, $req, @params);
611 if( ref($self) eq 'HASH') {
612 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$err\n", ERROR);
615 $SIG{__WARN__} = $warnhandler;
619 if(UNIVERSAL::isa($err,"Error")) {
627 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
629 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
630 $req->respond($resp) if (defined $resp);
631 $log->debug("SubRequest object is responding with : " . join(" ",$req->responses), DEBUG);
632 return $req->responses;
634 $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
638 my $session = OpenSRF::AppSession->create($self->{server_class});
640 #$session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
641 my $remote_req = $session->request( $self->{api_name}, @params );
642 while (my $remote_resp = $remote_req->recv) {
643 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
644 if( UNIVERSAL::isa($remote_resp,"Error") ) {
647 $req->respond( $remote_resp->content );
649 $remote_req->finish();
653 $log->debug( "Remote subrequest returned an error:\n". $e );
658 $session->disconnect();
662 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
664 return $req->responses;
666 # huh? how'd we get here...
677 if ($self->api_name =~ /all$/o) {
683 my ($seen,$returned) = (0,0);
684 for my $api_level ( reverse(1 .. $#_METHODS) ) {
685 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
686 if (!$offset || $offset <= $seen) {
687 if (!$_METHODS[$api_level]{$api_name}{remote}) {
688 if (defined($method)) {
689 if ($api_name =~ $method) {
690 if (!$limit || $returned < $limit) {
691 $client->respond( $_METHODS[$api_level]{$api_name} );
696 if (!$limit || $returned < $limit) {
697 $client->respond( $_METHODS[$api_level]{$api_name} );
709 __PACKAGE__->register_method(
711 method => 'introspect',
712 api_name => 'opensrf.system.method.all',
715 desc => q/This method is used to introspect an entire OpenSRF Application/,
717 desc => q/A stream of objects describing the methods available via this OpenSRF Application/,
722 __PACKAGE__->register_method(
724 method => 'introspect',
726 api_name => 'opensrf.system.method',
729 desc => q/Use this method to get the definition of a single OpenSRF Method/,
731 { desc => q/The method to introspect/,
734 return => { desc => q/An object describing the method requested, or an error if it can't be found/,
744 $client->respond( $_ ) for (@args);
747 __PACKAGE__->register_method(
749 method => 'echo_method',
751 api_name => 'opensrf.system.echo',
753 desc => q/A test method that will echo back it's arguments in a streaming response/,
755 { desc => q/One or more arguments to echo back/ }
757 return => { desc => q/A stream of the arguments passed/ }
762 my( $self, $conn ) = @_;
765 __PACKAGE__->register_method(
766 method => 'time_method',
768 api_name => 'opensrf.system.time',
770 desc => q/Returns the current system time as epoch seconds/,
771 return => { desc => q/epoch seconds/ }
775 sub make_stream_atomic {
780 (my $m_name = $self->api_name) =~ s/\.atomic$//o;
781 my $m = $self->method_lookup($m_name);
783 $m->session( $req->session );
784 my @results = $m->run(@args);