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( name => $args{package}, hint => $args{object_hint}, type => "hash" );
442 $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
444 __PACKAGE__->register_method(
447 api_name => $args{api_name}.'.atomic',
448 method => 'make_stream_atomic',
449 notes => "This is a system generated method. Please see the definition for $args{api_name}",
450 ) if ($args{stream});
453 sub retrieve_remote_apis {
455 my $session = OpenSRF::AppSession->create('router');
457 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
460 $log->debug( "Remote subrequest returned an error:\n". $e );
463 return undef unless ($session->state == $session->CONNECTED);
466 my $req = $session->request( 'opensrf.router.info.class.list' );
467 my $list = $req->recv;
469 if( UNIVERSAL::isa($list,"Error") ) {
473 my $content = $list->content;
477 $session->disconnect;
479 my %u_list = map { ($_ => 1) } @$content;
481 for my $class ( keys %u_list ) {
482 next if($class eq $server_class);
483 populate_remote_method_cache($class, $method);
487 sub populate_remote_method_cache {
491 my $session = OpenSRF::AppSession->create($class);
493 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
495 my $call = 'opensrf.system.method.all' unless (defined $meth);
496 $call = 'opensrf.system.method' if (defined $meth);
498 my $req = $session->request( $call, $meth );
500 while (my $method = $req->recv) {
501 next if (UNIVERSAL::isa($method, 'Error'));
503 $method = $method->content;
504 next if ( exists($_METHODS[$$method{api_level}]) &&
505 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
506 $method->{remote} = 1;
507 bless($method, __PACKAGE__ );
508 $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
513 $session->disconnect;
517 $log->debug( "Remote subrequest returned an error:\n". $e );
526 my $no_recurse = shift || 0;
527 my $no_remote = shift || 0;
529 # this instead of " || 1;" above to allow api_level 0
530 $proto = $self->api_level unless (defined $proto);
532 my $class = ref($self) || $self;
534 $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
535 $log->debug("Available methods\n\t".join("\n\t", keys %{ $_METHODS[$proto] }), INTERNAL);
538 if (__PACKAGE__->thunk) {
539 for my $p ( reverse(1 .. $proto) ) {
540 if (exists $_METHODS[$p]{$method}) {
541 $meth = $_METHODS[$p]{$method};
545 if (exists $_METHODS[$proto]{$method}) {
546 $meth = $_METHODS[$proto]{$method};
551 if($no_remote and $meth->{remote}) {
552 $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
556 } elsif (!$no_recurse) {
557 $log->debug("We didn't find [$method], asking everyone else.", DEBUG);
558 retrieve_remote_apis($method);
559 $meth = $self->method_lookup($method,$proto,1);
562 $meth->session($self->session) if $meth; # Pass the caller's session
573 if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
574 $log->debug("Creating a SubRequest object", DEBUG);
575 unshift @params, $req;
576 $req = OpenSRF::AppSubrequest->new( session => $self->session );
578 $log->debug("This is a top level request", DEBUG);
581 if (!$self->{remote}) {
582 my $code = \&{$self->{package} . '::' . $self->{method}};
587 $warnhandler = $SIG{__WARN__};
588 $SIG{__WARN__} = sub {
589 (my $msg = shift) =~ s/\n$//;
590 $log->warn($self->{api_name} . ": $msg");
591 return 1; # prevents warning going out to stderr
594 $resp = $code->($self, $req, @params);
599 if( ref($self) eq 'HASH') {
600 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$err\n", ERROR);
603 $SIG{__WARN__} = $warnhandler;
607 if(UNIVERSAL::isa($err,"Error")) {
615 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
617 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
618 $req->respond($resp) if (defined $resp);
619 $log->debug("SubRequest object is responding with : " . join(" ",$req->responses), DEBUG);
620 return $req->responses;
622 $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
626 my $session = OpenSRF::AppSession->create($self->{server_class});
628 #$session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
629 my $remote_req = $session->request( $self->{api_name}, @params );
630 while (my $remote_resp = $remote_req->recv) {
631 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
632 if( UNIVERSAL::isa($remote_resp,"Error") ) {
635 $req->respond( $remote_resp->content );
637 $remote_req->finish();
641 $log->debug( "Remote subrequest returned an error:\n". $e );
646 $session->disconnect();
650 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
652 return $req->responses;
654 # huh? how'd we get here...
665 if ($self->api_name =~ /all$/o) {
671 my ($seen,$returned) = (0,0);
672 for my $api_level ( reverse(1 .. $#_METHODS) ) {
673 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
674 if (!$offset || $offset <= $seen) {
675 if (!$_METHODS[$api_level]{$api_name}{remote}) {
676 if (defined($method)) {
677 if ($api_name =~ $method) {
678 if (!$limit || $returned < $limit) {
679 $client->respond( $_METHODS[$api_level]{$api_name} );
684 if (!$limit || $returned < $limit) {
685 $client->respond( $_METHODS[$api_level]{$api_name} );
697 __PACKAGE__->register_method(
699 method => 'introspect',
700 api_name => 'opensrf.system.method.all',
703 desc => q/This method is used to introspect an entire OpenSRF Application/,
705 desc => q/A stream of objects describing the methods available via this OpenSRF Application/,
710 __PACKAGE__->register_method(
712 method => 'introspect',
714 api_name => 'opensrf.system.method',
717 desc => q/Use this method to get the definition of a single OpenSRF Method/,
719 { desc => q/The method to introspect/,
722 return => { desc => q/An object describing the method requested, or an error if it can't be found/,
732 $client->respond( $_ ) for (@args);
735 __PACKAGE__->register_method(
737 method => 'echo_method',
739 api_name => 'opensrf.system.echo',
741 desc => q/A test method that will echo back it's arguments in a streaming response/,
743 { desc => q/One or more arguments to echo back/ }
745 return => { desc => q/A stream of the arguments passed/ }
750 my( $self, $conn ) = @_;
753 __PACKAGE__->register_method(
754 method => 'time_method',
756 api_name => 'opensrf.system.time',
758 desc => q/Returns the current system time as epoch seconds/,
759 return => { desc => q/epoch seconds/ }
763 sub make_stream_atomic {
768 (my $m_name = $self->api_name) =~ s/\.atomic$//o;
769 my $m = $self->method_lookup($m_name);
771 $m->session( $req->session );
772 my @results = $m->run(@args);