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(', ',@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 my $appreq = OpenSRF::AppRequest->new( $session );
175 $appreq->max_chunk_size( $coderef->max_chunk_size );
176 $appreq->max_chunk_count( $coderef->max_chunk_count );
178 $log->debug( "in_request = $in_request : [" . $appreq->threadTrace."]", INTERNAL );
180 $log->debug( "Pushing onto pending requests: " . $appreq->threadTrace, DEBUG );
181 push @pending_requests, [ $appreq, \@args, $coderef ];
188 $log->debug( "Executing coderef for {$method_name}", INTERNAL );
192 # un-if(0) this block to enable param checking based on signature and argc
193 if ($coderef->strict) {
194 if (@args < $coderef->argc) {
195 die "Not enough params passed to ".
196 $coderef->api_name." : requires ". $coderef->argc
199 my $sig = $coderef->signature;
200 if ($sig && exists $sig->{params}) {
201 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
202 my $s = $sig->{params}->[$p];
204 if ($s->{class} && OpenSRF::Utils::JSON->lookup_hint(ref $a) ne $s->{class}) {
205 die "Incorrect param class at position $p : should be a '$$s{class}'";
206 } elsif ($s->{type}) {
207 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
208 die "Incorrect param type at position $p : should be an 'object'";
209 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
210 die "Incorrect param type at position $p : should be an 'array'";
211 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
212 die "Incorrect param type at position $p : should be a 'number'";
213 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
214 die "Incorrect param type at position $p : should be a 'string'";
223 $resp = $coderef->run( $appreq, @args);
224 my $time = sprintf '%.3f', time() - $start;
226 $log->debug( "Method duration for [$method_name]: ". $time );
227 $appreq->respond_complete( $resp );
231 warn "Caught error from 'run' method: $e\n";
233 if(UNIVERSAL::isa($e,"Error")) {
234 $e = $e->stringify();
236 my $sess_id = $session->session_id;
238 OpenSRF::DomainObject::oilsMethodException->new(
239 statusCode => STATUS_INTERNALSERVERERROR(),
240 status => " *** Call to [$method_name] failed for session ".
241 "[$sess_id], thread trace ".
242 "[".$appreq->threadTrace."]:\n$e\n"
249 # ----------------------------------------------
252 # XXX may need this later
253 # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
257 $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
259 # cycle through queued requests
260 while( my $aref = shift @pending_requests ) {
264 # un-if(0) this block to enable param checking based on signature and argc
266 if (@args < $aref->[2]->argc) {
267 die "Not enough params passed to ".
268 $aref->[2]->api_name." : requires ". $aref->[2]->argc
271 my $sig = $aref->[2]->signature;
272 if ($sig && exists $sig->{params}) {
273 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
274 my $s = $sig->{params}->[$p];
276 if ($s->{class} && OpenSRF::Utils::JSON->lookup_hint(ref $a) ne $s->{class}) {
277 die "Incorrect param class at position $p : should be a '$$s{class}'";
278 } elsif ($s->{type}) {
279 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
280 die "Incorrect param type at position $p : should be an 'object'";
281 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
282 die "Incorrect param type at position $p : should be an 'array'";
283 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
284 die "Incorrect param type at position $p : should be a 'number'";
285 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
286 die "Incorrect param type at position $p : should be a 'string'";
295 my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
296 my $time = sprintf '%.3f', time - $start;
297 $log->debug( "Method duration for [".$aref->[2]->api_name." -> ".join(', ',@{$aref->[1]}).']: '.$time, DEBUG );
299 $appreq = $aref->[0];
300 $appreq->respond_complete( $response );
301 $log->debug( "Executed: " . $appreq->threadTrace, INTERNAL );
305 if(UNIVERSAL::isa($e,"Error")) {
306 $e = $e->stringify();
309 OpenSRF::DomainObject::oilsMethodException->new(
310 statusCode => STATUS_INTERNALSERVERERROR(),
311 status => "Call to [".$aref->[2]->api_name."] faild: $e"
321 $log->info("Received non-REQUEST message in Application handler");
323 my $res = OpenSRF::DomainObject::oilsMethodException->new(
324 status => "Received non-REQUEST message in Application handler");
325 $session->send('ERROR', $res);
330 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
333 $session->last_message_type('');
334 $session->last_message_api_level('');
341 my $api_name = shift;
342 my $api_level = shift || 1;
343 return exists($_METHODS[$api_level]{$api_name});
347 sub normalize_whitespace {
354 $txt =~ s/\. /\. /gso;
359 sub parse_string_signature {
361 return [] unless $string;
362 my @chunks = split(/\@/smo, $string);
368 if (/^return (.+)$/so) {
369 $ret = [normalize_whitespace($1)];
370 } elsif (/^param (\w+) \b(.+)$/so) {
371 push @params, [ $1, normalize_whitespace($2) ];
373 $desc .= '@' if $desc;
378 return [normalize_whitespace($desc),\@params, $ret];
381 sub parse_array_signature {
383 my ($d,$p,$r) = @$array;
384 return {} unless ($d or $p or $r);
405 sub register_method {
407 my $app = ref($self) || $self;
411 throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
413 $args{api_level} = 1 unless(defined($args{api_level}));
417 $args{package} ||= $app;
418 $args{server_class} = server_class();
419 $args{api_name} ||= $args{server_class} . '.' . $args{method};
421 # un-if(0) this block to enable signature parsing
422 if (!$args{signature}) {
423 if ($args{notes} && !ref($args{notes})) {
425 parse_array_signature( parse_string_signature( $args{notes} ) );
427 } elsif( !ref($args{signature}) ) {
429 parse_array_signature( parse_string_signature( $args{signature} ) );
430 } elsif( ref($args{signature}) eq 'ARRAY') {
432 parse_array_signature( $args{signature} );
435 unless ($args{object_hint}) {
436 ($args{object_hint} = $args{package}) =~ s/::/_/go;
439 OpenSRF::Utils::JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
441 $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
443 __PACKAGE__->register_method(
446 api_name => $args{api_name}.'.atomic',
447 method => 'make_stream_atomic',
448 notes => "This is a system generated method. Please see the definition for $args{api_name}",
449 ) if ($args{stream});
452 sub retrieve_remote_apis {
454 my $session = OpenSRF::AppSession->create('router');
456 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
459 $log->debug( "Remote subrequest returned an error:\n". $e );
462 return undef unless ($session->state == $session->CONNECTED);
465 my $req = $session->request( 'opensrf.router.info.class.list' );
466 my $list = $req->recv;
468 if( UNIVERSAL::isa($list,"Error") ) {
472 my $content = $list->content;
476 $session->disconnect;
478 my %u_list = map { ($_ => 1) } @$content;
480 for my $class ( keys %u_list ) {
481 next if($class eq $server_class);
482 populate_remote_method_cache($class, $method);
486 sub populate_remote_method_cache {
490 my $session = OpenSRF::AppSession->create($class);
492 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
494 my $call = 'opensrf.system.method.all' unless (defined $meth);
495 $call = 'opensrf.system.method' if (defined $meth);
497 my $req = $session->request( $call, $meth );
499 while (my $method = $req->recv) {
500 next if (UNIVERSAL::isa($method, 'Error'));
502 $method = $method->content;
503 next if ( exists($_METHODS[$$method{api_level}]) &&
504 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
505 $method->{remote} = 1;
506 bless($method, __PACKAGE__ );
507 $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
512 $session->disconnect;
516 $log->debug( "Remote subrequest returned an error:\n". $e );
525 my $no_recurse = shift || 0;
526 my $no_remote = shift || 0;
528 # this instead of " || 1;" above to allow api_level 0
529 $proto = $self->api_level unless (defined $proto);
531 my $class = ref($self) || $self;
533 $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
534 $log->debug("Available methods\n\t".join("\n\t", keys %{ $_METHODS[$proto] }), INTERNAL);
537 if (__PACKAGE__->thunk) {
538 for my $p ( reverse(1 .. $proto) ) {
539 if (exists $_METHODS[$p]{$method}) {
540 $meth = $_METHODS[$p]{$method};
544 if (exists $_METHODS[$proto]{$method}) {
545 $meth = $_METHODS[$proto]{$method};
550 if($no_remote and $meth->{remote}) {
551 $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
555 } elsif (!$no_recurse) {
556 $log->debug("We didn't find [$method], asking everyone else.", DEBUG);
557 retrieve_remote_apis($method);
558 $meth = $self->method_lookup($method,$proto,1);
571 if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
572 $log->debug("Creating a SubRequest object", DEBUG);
573 unshift @params, $req;
574 $req = OpenSRF::AppSubrequest->new;
575 $req->session( $self->session ) if ($self->session);
578 $log->debug("This is a top level request", DEBUG);
581 if (!$self->{remote}) {
582 my $code = \&{$self->{package} . '::' . $self->{method}};
586 $resp = $code->($self, $req, @params);
591 if( ref($self) eq 'HASH') {
592 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$err\n", ERROR);
597 if(UNIVERSAL::isa($err,"Error")) {
605 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
607 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
608 $req->respond($resp) if (defined $resp);
609 $log->debug("SubRequest object is responding with : " . join(" ",$req->responses), DEBUG);
610 return $req->responses;
612 $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
616 my $session = OpenSRF::AppSession->create($self->{server_class});
618 #$session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
619 my $remote_req = $session->request( $self->{api_name}, @params );
620 while (my $remote_resp = $remote_req->recv) {
621 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
622 if( UNIVERSAL::isa($remote_resp,"Error") ) {
625 $req->respond( $remote_resp->content );
627 $remote_req->finish();
631 $log->debug( "Remote subrequest returned an error:\n". $e );
636 $session->disconnect();
640 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
642 return $req->responses;
644 # huh? how'd we get here...
655 if ($self->api_name =~ /all$/o) {
661 my ($seen,$returned) = (0,0);
662 for my $api_level ( reverse(1 .. $#_METHODS) ) {
663 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
664 if (!$offset || $offset <= $seen) {
665 if (!$_METHODS[$api_level]{$api_name}{remote}) {
666 if (defined($method)) {
667 if ($api_name =~ $method) {
668 if (!$limit || $returned < $limit) {
669 $client->respond( $_METHODS[$api_level]{$api_name} );
674 if (!$limit || $returned < $limit) {
675 $client->respond( $_METHODS[$api_level]{$api_name} );
687 __PACKAGE__->register_method(
689 method => 'introspect',
690 api_name => 'opensrf.system.method.all',
693 desc => q/This method is used to introspect an entire OpenSRF Application/,
695 desc => q/A stream of objects describing the methods available via this OpenSRF Application/,
700 __PACKAGE__->register_method(
702 method => 'introspect',
704 api_name => 'opensrf.system.method',
707 desc => q/Use this method to get the definition of a single OpenSRF Method/,
709 { desc => q/The method to introspect/,
712 return => { desc => q/An object describing the method requested, or an error if it can't be found/,
722 $client->respond( $_ ) for (@args);
725 __PACKAGE__->register_method(
727 method => 'echo_method',
729 api_name => 'opensrf.system.echo',
731 desc => q/A test method that will echo back it's arguments in a streaming response/,
733 { desc => q/One or more arguments to echo back/ }
735 return => { desc => q/A stream of the arguments passed/ }
740 my( $self, $conn ) = @_;
743 __PACKAGE__->register_method(
744 method => 'time_method',
746 api_name => 'opensrf.system.time',
748 desc => q/Returns the current system time as epoch seconds/,
749 return => { desc => q/epoch seconds/ }
753 sub make_stream_atomic {
758 (my $m_name = $self->api_name) =~ s/\.atomic$//o;
759 my $m = $self->method_lookup($m_name);
761 $m->session( $req->session );
762 my @results = $m->run(@args);