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 foreach my $match_string (@{$shared_conf->shared->log_protect}) {
139 if ($method_name =~ /^$match_string/) {
144 if ($redact_params) {
145 $logdata .= "**PARAMS REDACTED**";
147 $logdata .= join(', ',@p);
150 $log->info($logdata);
152 my $coderef = $app->method_lookup( $method_name, $method_proto, 1, 1 );
155 $session->status( OpenSRF::DomainObject::oilsMethodException->new(
156 statusCode => STATUS_NOTFOUND(),
157 status => "Method [$method_name] not found for $app"));
161 unless ($session->continue_request) {
163 OpenSRF::DomainObject::oilsConnectStatus->new(
164 statusCode => STATUS_REDIRECTED(),
165 status => 'Disconnect on max requests' ) );
171 my @args = $app_msg->params;
172 my $appreq = OpenSRF::AppRequest->new( $session );
173 $appreq->max_chunk_size( $coderef->max_chunk_size );
174 $appreq->max_chunk_count( $coderef->max_chunk_count );
176 $log->debug( "in_request = $in_request : [" . $appreq->threadTrace."]", INTERNAL );
178 $log->debug( "Pushing onto pending requests: " . $appreq->threadTrace, DEBUG );
179 push @pending_requests, [ $appreq, \@args, $coderef ];
186 $log->debug( "Executing coderef for {$method_name}", INTERNAL );
190 # un-if(0) this block to enable param checking based on signature and argc
191 if ($coderef->strict) {
192 if (@args < $coderef->argc) {
193 die "Not enough params passed to ".
194 $coderef->api_name." : requires ". $coderef->argc
197 my $sig = $coderef->signature;
198 if ($sig && exists $sig->{params}) {
199 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
200 my $s = $sig->{params}->[$p];
202 if ($s->{class} && OpenSRF::Utils::JSON->lookup_hint(ref $a) ne $s->{class}) {
203 die "Incorrect param class at position $p : should be a '$$s{class}'";
204 } elsif ($s->{type}) {
205 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
206 die "Incorrect param type at position $p : should be an 'object'";
207 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
208 die "Incorrect param type at position $p : should be an 'array'";
209 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
210 die "Incorrect param type at position $p : should be a 'number'";
211 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
212 die "Incorrect param type at position $p : should be a 'string'";
221 $resp = $coderef->run( $appreq, @args);
222 my $time = sprintf '%.3f', time() - $start;
224 $log->debug( "Method duration for [$method_name]: ". $time );
225 $appreq->respond_complete( $resp );
229 warn "Caught error from 'run' method: $e\n";
231 if(UNIVERSAL::isa($e,"Error")) {
232 $e = $e->stringify();
234 my $sess_id = $session->session_id;
236 OpenSRF::DomainObject::oilsMethodException->new(
237 statusCode => STATUS_INTERNALSERVERERROR(),
238 status => " *** Call to [$method_name] failed for session ".
239 "[$sess_id], thread trace ".
240 "[".$appreq->threadTrace."]:\n$e\n"
247 # ----------------------------------------------
250 # XXX may need this later
251 # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
255 $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
257 # cycle through queued requests
258 while( my $aref = shift @pending_requests ) {
262 # un-if(0) this block to enable param checking based on signature and argc
264 if (@args < $aref->[2]->argc) {
265 die "Not enough params passed to ".
266 $aref->[2]->api_name." : requires ". $aref->[2]->argc
269 my $sig = $aref->[2]->signature;
270 if ($sig && exists $sig->{params}) {
271 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
272 my $s = $sig->{params}->[$p];
274 if ($s->{class} && OpenSRF::Utils::JSON->lookup_hint(ref $a) ne $s->{class}) {
275 die "Incorrect param class at position $p : should be a '$$s{class}'";
276 } elsif ($s->{type}) {
277 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
278 die "Incorrect param type at position $p : should be an 'object'";
279 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
280 die "Incorrect param type at position $p : should be an 'array'";
281 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
282 die "Incorrect param type at position $p : should be a 'number'";
283 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
284 die "Incorrect param type at position $p : should be a 'string'";
293 my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
294 my $time = sprintf '%.3f', time - $start;
295 $log->debug( "Method duration for [".$aref->[2]->api_name." -> ".join(', ',@{$aref->[1]}).']: '.$time, DEBUG );
297 $appreq = $aref->[0];
298 $appreq->respond_complete( $response );
299 $log->debug( "Executed: " . $appreq->threadTrace, INTERNAL );
303 if(UNIVERSAL::isa($e,"Error")) {
304 $e = $e->stringify();
307 OpenSRF::DomainObject::oilsMethodException->new(
308 statusCode => STATUS_INTERNALSERVERERROR(),
309 status => "Call to [".$aref->[2]->api_name."] faild: $e"
319 $log->info("Received non-REQUEST message in Application handler");
321 my $res = OpenSRF::DomainObject::oilsMethodException->new(
322 status => "Received non-REQUEST message in Application handler");
323 $session->send('ERROR', $res);
328 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
331 $session->last_message_type('');
332 $session->last_message_api_level('');
339 my $api_name = shift;
340 my $api_level = shift || 1;
341 return exists($_METHODS[$api_level]{$api_name});
345 sub normalize_whitespace {
352 $txt =~ s/\. /\. /gso;
357 sub parse_string_signature {
359 return [] unless $string;
360 my @chunks = split(/\@/smo, $string);
366 if (/^return (.+)$/so) {
367 $ret = [normalize_whitespace($1)];
368 } elsif (/^param (\w+) \b(.+)$/so) {
369 push @params, [ $1, normalize_whitespace($2) ];
371 $desc .= '@' if $desc;
376 return [normalize_whitespace($desc),\@params, $ret];
379 sub parse_array_signature {
381 my ($d,$p,$r) = @$array;
382 return {} unless ($d or $p or $r);
403 sub register_method {
405 my $app = ref($self) || $self;
409 throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
411 $args{api_level} = 1 unless(defined($args{api_level}));
415 $args{package} ||= $app;
416 $args{server_class} = server_class();
417 $args{api_name} ||= $args{server_class} . '.' . $args{method};
419 # un-if(0) this block to enable signature parsing
420 if (!$args{signature}) {
421 if ($args{notes} && !ref($args{notes})) {
423 parse_array_signature( parse_string_signature( $args{notes} ) );
425 } elsif( !ref($args{signature}) ) {
427 parse_array_signature( parse_string_signature( $args{signature} ) );
428 } elsif( ref($args{signature}) eq 'ARRAY') {
430 parse_array_signature( $args{signature} );
433 unless ($args{object_hint}) {
434 ($args{object_hint} = $args{package}) =~ s/::/_/go;
437 OpenSRF::Utils::JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
439 $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
441 __PACKAGE__->register_method(
444 api_name => $args{api_name}.'.atomic',
445 method => 'make_stream_atomic',
446 notes => "This is a system generated method. Please see the definition for $args{api_name}",
447 ) if ($args{stream});
450 sub retrieve_remote_apis {
452 my $session = OpenSRF::AppSession->create('router');
454 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
457 $log->debug( "Remote subrequest returned an error:\n". $e );
460 return undef unless ($session->state == $session->CONNECTED);
463 my $req = $session->request( 'opensrf.router.info.class.list' );
464 my $list = $req->recv;
466 if( UNIVERSAL::isa($list,"Error") ) {
470 my $content = $list->content;
474 $session->disconnect;
476 my %u_list = map { ($_ => 1) } @$content;
478 for my $class ( keys %u_list ) {
479 next if($class eq $server_class);
480 populate_remote_method_cache($class, $method);
484 sub populate_remote_method_cache {
488 my $session = OpenSRF::AppSession->create($class);
490 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
492 my $call = 'opensrf.system.method.all' unless (defined $meth);
493 $call = 'opensrf.system.method' if (defined $meth);
495 my $req = $session->request( $call, $meth );
497 while (my $method = $req->recv) {
498 next if (UNIVERSAL::isa($method, 'Error'));
500 $method = $method->content;
501 next if ( exists($_METHODS[$$method{api_level}]) &&
502 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
503 $method->{remote} = 1;
504 bless($method, __PACKAGE__ );
505 $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
510 $session->disconnect;
514 $log->debug( "Remote subrequest returned an error:\n". $e );
523 my $no_recurse = shift || 0;
524 my $no_remote = shift || 0;
526 # this instead of " || 1;" above to allow api_level 0
527 $proto = $self->api_level unless (defined $proto);
529 my $class = ref($self) || $self;
531 $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
532 $log->debug("Available methods\n\t".join("\n\t", keys %{ $_METHODS[$proto] }), INTERNAL);
535 if (__PACKAGE__->thunk) {
536 for my $p ( reverse(1 .. $proto) ) {
537 if (exists $_METHODS[$p]{$method}) {
538 $meth = $_METHODS[$p]{$method};
542 if (exists $_METHODS[$proto]{$method}) {
543 $meth = $_METHODS[$proto]{$method};
548 if($no_remote and $meth->{remote}) {
549 $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
553 } elsif (!$no_recurse) {
554 $log->debug("We didn't find [$method], asking everyone else.", DEBUG);
555 retrieve_remote_apis($method);
556 $meth = $self->method_lookup($method,$proto,1);
569 if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
570 $log->debug("Creating a SubRequest object", DEBUG);
571 unshift @params, $req;
572 $req = OpenSRF::AppSubrequest->new;
573 $req->session( $self->session ) if ($self->session);
576 $log->debug("This is a top level request", DEBUG);
579 if (!$self->{remote}) {
580 my $code = \&{$self->{package} . '::' . $self->{method}};
584 $resp = $code->($self, $req, @params);
589 if( ref($self) eq 'HASH') {
590 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$err\n", ERROR);
595 if(UNIVERSAL::isa($err,"Error")) {
603 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
605 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
606 $req->respond($resp) if (defined $resp);
607 $log->debug("SubRequest object is responding with : " . join(" ",$req->responses), DEBUG);
608 return $req->responses;
610 $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
614 my $session = OpenSRF::AppSession->create($self->{server_class});
616 #$session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
617 my $remote_req = $session->request( $self->{api_name}, @params );
618 while (my $remote_resp = $remote_req->recv) {
619 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
620 if( UNIVERSAL::isa($remote_resp,"Error") ) {
623 $req->respond( $remote_resp->content );
625 $remote_req->finish();
629 $log->debug( "Remote subrequest returned an error:\n". $e );
634 $session->disconnect();
638 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
640 return $req->responses;
642 # huh? how'd we get here...
653 if ($self->api_name =~ /all$/o) {
659 my ($seen,$returned) = (0,0);
660 for my $api_level ( reverse(1 .. $#_METHODS) ) {
661 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
662 if (!$offset || $offset <= $seen) {
663 if (!$_METHODS[$api_level]{$api_name}{remote}) {
664 if (defined($method)) {
665 if ($api_name =~ $method) {
666 if (!$limit || $returned < $limit) {
667 $client->respond( $_METHODS[$api_level]{$api_name} );
672 if (!$limit || $returned < $limit) {
673 $client->respond( $_METHODS[$api_level]{$api_name} );
685 __PACKAGE__->register_method(
687 method => 'introspect',
688 api_name => 'opensrf.system.method.all',
691 desc => q/This method is used to introspect an entire OpenSRF Application/,
693 desc => q/A stream of objects describing the methods available via this OpenSRF Application/,
698 __PACKAGE__->register_method(
700 method => 'introspect',
702 api_name => 'opensrf.system.method',
705 desc => q/Use this method to get the definition of a single OpenSRF Method/,
707 { desc => q/The method to introspect/,
710 return => { desc => q/An object describing the method requested, or an error if it can't be found/,
720 $client->respond( $_ ) for (@args);
723 __PACKAGE__->register_method(
725 method => 'echo_method',
727 api_name => 'opensrf.system.echo',
729 desc => q/A test method that will echo back it's arguments in a streaming response/,
731 { desc => q/One or more arguments to echo back/ }
733 return => { desc => q/A stream of the arguments passed/ }
738 my( $self, $conn ) = @_;
741 __PACKAGE__->register_method(
742 method => 'time_method',
744 api_name => 'opensrf.system.time',
746 desc => q/Returns the current system time as epoch seconds/,
747 return => { desc => q/epoch seconds/ }
751 sub make_stream_atomic {
756 (my $m_name = $self->api_name) =~ s/\.atomic$//o;
757 my $m = $self->method_lookup($m_name);
759 $m->session( $req->session );
760 my @results = $m->run(@args);