1 package OpenSRF::Application;
2 use vars qw/$_app $log @_METHODS $thunk $server_class/;
5 use OpenSRF::AppSession;
6 use OpenSRF::DomainObject::oilsMethod;
7 use OpenSRF::DomainObject::oilsResponse qw/:status/;
8 use OpenSRF::Utils::Logger qw/:level/;
10 use Time::HiRes qw/time/;
11 use OpenSRF::EX qw/:try/;
13 #use OpenSRF::UnixServer; # to get the server class from UnixServer::App
20 $log = 'OpenSRF::Utils::Logger';
23 our @pending_requests;
27 return 1 unless ref($self);
28 return $self->{package};
33 return 1 unless ref($self);
34 return $self->{api_name};
39 return 1 unless ref($self);
40 return $self->{api_level};
46 $server_class = $class;
54 $thunk = $flag if (defined $flag);
58 sub application_implementation {
66 $log->error( "Error loading application_implementation: $app -> $@", ERROR);
75 my ($self, $session, $app_msg) = @_;
81 $log->debug( "In Application::handler()", DEBUG );
83 my $app = $self->application_implementation;
86 $log->debug( "Application is $app", DEBUG);
88 $log->debug( "Message is ".$app_msg->toString(1), INTERNAL);
91 if ($session->last_message_type eq 'REQUEST') {
92 $log->debug( "We got a REQUEST: ". $app_msg->method, INFO );
94 my $method_name = $app_msg->method;
95 $log->debug( " * Looking up $method_name inside $app", DEBUG);
97 my $method_proto = $session->last_message_api_level;
98 $log->debug( " * Method API Level [$method_proto]", DEBUG);
100 my $coderef = $app->method_lookup( $method_name, $method_proto, 1, 1 );
103 $session->status( OpenSRF::DomainObject::oilsMethodException->new() );
107 $log->debug( " (we got coderef $coderef", DEBUG);
109 unless ($session->continue_request) {
111 OpenSRF::DomainObject::oilsConnectStatus->new(
112 statusCode => STATUS_REDIRECTED(),
113 status => 'Disconnect on max requests' ) );
119 my @args = $app_msg->params;
120 my $appreq = OpenSRF::AppRequest->new( $session );
122 $log->debug( "in_request = $in_request : [" . $appreq->threadTrace."]", DEBUG );
124 $log->debug( "Pushing onto pending requests: " . $appreq->threadTrace, DEBUG );
125 push @pending_requests, [ $appreq, \@args, $coderef ];
132 $log->debug( "Executing coderef for {$method_name -> ".join(', ', @args)."}", INTERNAL );
137 $resp = $coderef->run( $appreq, @args);
138 my $time = sprintf '%.3f', time() - $start;
139 $log->debug( "Method duration for {$method_name -> ".join(', ', @args)."}: ". $time, DEBUG );
140 if( defined( $resp ) ) {
141 #$log->debug( "Calling respond_complete: ". $resp->toString(), INTERNAL );
142 $appreq->respond_complete( $resp );
144 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
145 statusCode => STATUS_COMPLETE(),
146 status => 'Request Complete' ) );
150 if(UNIVERSAL::isa($e,"Error")) {
151 $e = $e->stringify();
153 my $sess_id = $session->session_id;
155 OpenSRF::DomainObject::oilsMethodException->new(
156 statusCode => STATUS_INTERNALSERVERERROR(),
157 status => " *** Call to [$method_name] failed for session ".
158 "[$sess_id], thread trace [".$appreq->threadTrace."]:\n$e"
165 # ----------------------------------------------
168 # XXX may need this later
169 # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
173 $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
175 # cycle through queued requests
176 while( my $aref = shift @pending_requests ) {
181 my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
182 my $time = sprintf '%.3f', time - $start;
183 $log->debug( "Method duration for {[".$aref->[2]->api_name." -> ".join(', ',@{$aref->[1]}).'}: '.$time, DEBUG );
185 $appreq = $aref->[0];
186 if( ref( $response ) ) {
187 #$log->debug( "Calling respond_complete: ". $response->toString(), INTERNAL );
188 $appreq->respond_complete( $response );
190 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
191 statusCode => STATUS_COMPLETE(),
192 status => 'Request Complete' ) );
194 $log->debug( "Executed: " . $appreq->threadTrace, DEBUG );
197 if(UNIVERSAL::isa($e,"Error")) {
198 $e = $e->stringify();
201 OpenSRF::DomainObject::oilsMethodException->new(
202 statusCode => STATUS_INTERNALSERVERERROR(),
203 status => "Call to [".$aref->[2]->api_name."] faild: $e"
212 my $res = OpenSRF::DomainObject::oilsMethodException->new;
213 $session->send('ERROR', $res);
218 $log->debug( "Pushing ". $app_msg->toString ." onto queue", INTERNAL );
219 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
222 $session->last_message_type('');
223 $session->last_message_api_level('');
230 my $api_name = shift;
231 my $api_level = shift || 1;
232 return exists($_METHODS[$api_level]{$api_name});
235 sub register_method {
237 my $app = ref($self) || $self;
241 throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
243 $args{api_level} ||= 1;
246 $args{package} ||= $app;
247 $args{server_class} = server_class();
248 $args{api_name} ||= $args{server_class} . '.' . $args{method};
250 unless ($args{object_hint}) {
251 ($args{object_hint} = $args{package}) =~ s/::/_/go;
254 JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
256 $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
258 __PACKAGE__->register_method(
260 api_name => $args{api_name}.'.atomic',
261 method => 'make_stream_atomic'
262 ) if ($args{stream});
265 sub retrieve_remote_apis {
266 my $session = OpenSRF::AppSession->create('router');
268 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
271 $log->debug( "Remote subrequest returned an error:\n". $e );
274 return undef unless ($session->state == $session->CONNECTED);
277 my $req = $session->request( 'opensrf.router.info.class.list' );
278 my $list = $req->recv;
280 if( UNIVERSAL::isa($list,"Error") ) {
284 my $content = $list->content;
288 $session->disconnect;
290 my %u_list = map { ($_ => 1) } @$content;
292 for my $class ( keys %u_list ) {
293 next if($class eq $server_class);
294 populate_remote_method_cache($class);
298 sub populate_remote_method_cache {
301 my $session = OpenSRF::AppSession->create($class);
303 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
305 my $req = $session->request( 'opensrf.system.method.all' );
307 while (my $method = $req->recv) {
308 next if (UNIVERSAL::isa($method, 'Error'));
310 $method = $method->content;
311 next if ( exists($_METHODS[$$method{api_level}]) &&
312 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
313 $method->{remote} = 1;
314 bless($method, __PACKAGE__ );
315 $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
320 $session->disconnect;
324 $log->debug( "Remote subrequest returned an error:\n". $e );
333 my $no_recurse = shift || 0;
334 my $no_remote = shift || 0;
336 # this instead of " || 1;" above to allow api_level 0
337 $proto = $self->api_level unless (defined $proto);
339 my $class = ref($self) || $self;
341 $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
342 #$log->debug("Available methods\n".Dumper(\@_METHODS), INTERNAL);
345 if (__PACKAGE__->thunk) {
346 for my $p ( reverse(1 .. $proto) ) {
347 if (exists $_METHODS[$p]{$method}) {
348 $meth = $_METHODS[$p]{$method};
352 if (exists $_METHODS[$proto]{$method}) {
353 $meth = $_METHODS[$proto]{$method};
358 $log->debug("Looks like we found [$method]!", DEBUG);
359 $log->debug("Method object is ".Dumper($meth), INTERNAL);
360 if($no_remote and $meth->{remote}) {
361 $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
365 } elsif (!$no_recurse) {
366 retrieve_remote_apis();
367 $meth = $self->method_lookup($method,$proto,1);
380 if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
381 $log->debug("Creating a SubRequest object", DEBUG);
382 unshift @params, $req;
383 $req = OpenSRF::AppSubrequest->new;
385 $log->debug("This is a top level request", DEBUG);
388 if (!$self->{remote}) {
389 my $code ||= \&{$self->{package} . '::' . $self->{method}};
390 $log->debug("Created coderef [$code] for $$self{package}::$$self{method}",DEBUG);
394 $resp = $code->($self, $req, @params);
399 warn "Caught Error in Application: $e\n";
401 if( UNIVERSAL::isa($e,"Error")) {
402 warn "Exception is:\n " . $e->stringify() . "\n";
405 if( ref($self) eq 'HASH') {
407 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$e\n", ERROR);
412 if(UNIVERSAL::isa($err,"Error")) {
413 throw $err ($err->stringify);
420 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
422 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
423 $log->debug("A SubRequest object is responding", DEBUG);
424 $req->respond($resp) if (defined $resp);
425 $log->debug("... Responding with : " . join(" ",$req->responses), DEBUG);
426 return $req->responses;
428 $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
432 my $session = OpenSRF::AppSession->create($self->{server_class});
434 $session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
435 my $remote_req = $session->request( $self->{api_name}, @params );
436 while (my $remote_resp = $remote_req->recv) {
437 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
438 if( UNIVERSAL::isa($remote_resp,"Error") ) {
441 $req->respond( $remote_resp->content );
443 $remote_req->finish();
444 $session->disconnect();
449 $log->debug( "Remote subrequest returned an error:\n". $e );
453 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
455 return $req->responses;
457 # huh? how'd we get here...
466 $method = undef if ($self->api_name =~ /all$/o);
468 for my $api_level ( reverse(1 .. $#_METHODS) ) {
469 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
470 if (!$_METHODS[$api_level]{$api_name}{remote}) {
471 if (defined($method)) {
472 if ($api_name eq $method) {
473 $client->respond( $_METHODS[$api_level]{$api_name} );
476 $log->debug( "Returning definition for method [$api_name]", INTERNAL );
477 $client->respond( $_METHODS[$api_level]{$api_name} );
478 $log->debug( "responed with definition for method [$api_name]", INTERNAL );
486 __PACKAGE__->register_method(
488 method => 'introspect',
489 api_name => 'opensrf.system.method.all'
492 __PACKAGE__->register_method(
494 method => 'introspect',
496 api_name => 'opensrf.system.method'
499 sub make_stream_atomic {
504 (my $m_name = $self->api_name) =~ s/\.atomic$//o;
505 my @results = $self->method_lookup($m_name)->run(@args);