]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/perlmods/OpenSRF/Application.pm
method not found now returns the name of the method and package
[OpenSRF.git] / src / perlmods / OpenSRF / Application.pm
1 package OpenSRF::Application;
2 use vars qw/$_app $log @_METHODS $thunk $server_class/;
3
4 use base qw/OpenSRF/;
5 use OpenSRF::AppSession;
6 use OpenSRF::DomainObject::oilsMethod;
7 use OpenSRF::DomainObject::oilsResponse qw/:status/;
8 use OpenSRF::Utils::Logger qw/:level/;
9 use Data::Dumper;
10 use Time::HiRes qw/time/;
11 use OpenSRF::EX qw/:try/;
12 use Carp;
13 #use OpenSRF::UnixServer;  # to get the server class from UnixServer::App
14
15 sub DESTROY{};
16
17 use strict;
18 use warnings;
19
20 $log = 'OpenSRF::Utils::Logger';
21
22 our $in_request = 0;
23 our @pending_requests;
24
25 sub package {
26         my $self = shift;
27         return 1 unless ref($self);
28         return $self->{package};
29 }
30
31 sub api_name {
32         my $self = shift;
33         return 1 unless ref($self);
34         return $self->{api_name};
35 }
36
37 sub api_level {
38         my $self = shift;
39         return 1 unless ref($self);
40         return $self->{api_level};
41 }
42
43 sub server_class {
44         my $class = shift;
45         if($class) {
46                 $server_class = $class;
47         }
48         return $server_class;
49 }
50
51 sub thunk {
52         my $self = shift;
53         my $flag = shift;
54         $thunk = $flag if (defined $flag);
55         return $thunk;
56 }
57
58 sub application_implementation {
59         my $self = shift;
60         my $app = shift;
61
62         if (defined $app) {
63                 $_app = $app;
64                 eval "use $_app;";
65                 if( $@ ) {
66                         $log->error( "Error loading application_implementation: $app -> $@", ERROR);
67                 }
68
69         }
70
71         return $_app;
72 }
73
74 sub handler {
75         my ($self, $session, $app_msg) = @_;
76
77         if( ! $app_msg ) {
78                 return 1;  # error?
79         }
80
81         $log->debug( "In Application::handler()", DEBUG );
82
83         my $app = $self->application_implementation;
84
85         if( $app ) {
86                 $log->debug( "Application is $app", DEBUG);
87         }
88         $log->debug( "Message is ".$app_msg->toString(1), INTERNAL);
89
90
91         if ($session->last_message_type eq 'REQUEST') {
92                 $log->debug( "We got a REQUEST: ". $app_msg->method, INFO );
93
94                 my $method_name = $app_msg->method;
95                 $log->debug( " * Looking up $method_name inside $app", DEBUG);
96
97                 my $method_proto = $session->last_message_api_level;
98                 $log->debug( " * Method API Level [$method_proto]", DEBUG);
99
100                 my $coderef = $app->method_lookup( $method_name, $method_proto, 1, 1 );
101
102                 unless ($coderef) {
103                         $session->status( OpenSRF::DomainObject::oilsMethodException->new( 
104                                                 status => "Method [$method_name] not found for $app"));
105                         return 1;
106                 }
107
108                 $log->debug( " (we got coderef $coderef", DEBUG);
109
110                 unless ($session->continue_request) {
111                         $session->status(
112                                 OpenSRF::DomainObject::oilsConnectStatus->new(
113                                                 statusCode => STATUS_REDIRECTED(),
114                                                 status => 'Disconnect on max requests' ) );
115                         $session->kill_me;
116                         return 1;
117                 }
118
119                 if (ref $coderef) {
120                         my @args = $app_msg->params;
121                         my $appreq = OpenSRF::AppRequest->new( $session );
122
123                         $log->debug( "in_request = $in_request : [" . $appreq->threadTrace."]", DEBUG );
124                         if( $in_request ) {
125                                 $log->debug( "Pushing onto pending requests: " . $appreq->threadTrace, DEBUG );
126                                 push @pending_requests, [ $appreq, \@args, $coderef ]; 
127                                 return 1;
128                         }
129
130
131                         $in_request++;
132
133                         $log->debug( "Executing coderef for {$method_name -> ".join(', ', @args)."}", INTERNAL );
134
135                         my $resp;
136                         try {
137                                 my $start = time();
138                                 $resp = $coderef->run( $appreq, @args); 
139                                 my $time = sprintf '%.3f', time() - $start;
140                                 $log->debug( "Method duration for {$method_name -> ".join(', ', @args)."}:  ". $time, DEBUG );
141                                 if( defined( $resp ) ) {
142                                         #$log->debug( "Calling respond_complete: ". $resp->toString(), INTERNAL );
143                                         $appreq->respond_complete( $resp );
144                                 } else {
145                                         $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
146                                                                 statusCode => STATUS_COMPLETE(),
147                                                                 status => 'Request Complete' ) );
148                                 }
149                         } catch Error with {
150                                 my $e = shift;
151                                 if(UNIVERSAL::isa($e,"Error")) {
152                                         $e = $e->stringify();
153                                 } 
154                                 my $sess_id = $session->session_id;
155                                 $session->status(
156                                         OpenSRF::DomainObject::oilsMethodException->new(
157                                                         statusCode      => STATUS_INTERNALSERVERERROR(),
158                                                         status          => " *** Call to [$method_name] failed for session ".
159                                                                            "[$sess_id], thread trace [".$appreq->threadTrace."]:\n$e"
160                                         )
161                                 );
162                         };
163
164
165
166                         # ----------------------------------------------
167
168
169                         # XXX may need this later
170                         # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
171
172                         $in_request--;
173
174                         $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
175
176                         # cycle through queued requests
177                         while( my $aref = shift @pending_requests ) {
178                                 $in_request++;
179                                 my $resp;
180                                 try {
181                                         my $start = time;
182                                         my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
183                                         my $time = sprintf '%.3f', time - $start;
184                                         $log->debug( "Method duration for {[".$aref->[2]->api_name." -> ".join(', ',@{$aref->[1]}).'}:  '.$time, DEBUG );
185
186                                         $appreq = $aref->[0];   
187                                         if( ref( $response ) ) {
188                                                 #$log->debug( "Calling respond_complete: ". $response->toString(), INTERNAL );
189                                                 $appreq->respond_complete( $response );
190                                         } else {
191                                                 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
192                                                                         statusCode => STATUS_COMPLETE(),
193                                                                         status => 'Request Complete' ) );
194                                         }
195                                         $log->debug( "Executed: " . $appreq->threadTrace, DEBUG );
196                                 } catch Error with {
197                                         my $e = shift;
198                                         if(UNIVERSAL::isa($e,"Error")) {
199                                                 $e = $e->stringify();
200                                         }
201                                         $session->status(
202                                                 OpenSRF::DomainObject::oilsMethodException->new(
203                                                                 statusCode => STATUS_INTERNALSERVERERROR(),
204                                                                 status => "Call to [".$aref->[2]->api_name."] faild:  $e"
205                                                 )
206                                         );
207                                 };
208                                 $in_request--;
209                         }
210
211                         return 1;
212                 } 
213                 my $res = OpenSRF::DomainObject::oilsMethodException->new;
214                 $session->send('ERROR', $res);
215                 $session->kill_me;
216                 return 1;
217
218         } else {
219                 $log->debug( "Pushing ". $app_msg->toString ." onto queue", INTERNAL );
220                 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
221         }
222
223         $session->last_message_type('');
224         $session->last_message_api_level('');
225
226         return 1;
227 }
228
229 sub is_registered {
230         my $self = shift;
231         my $api_name = shift;
232         my $api_level = shift || 1;
233         return exists($_METHODS[$api_level]{$api_name});
234 }
235
236 sub register_method {
237         my $self = shift;
238         my $app = ref($self) || $self;
239         my %args = @_;
240
241
242         throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
243
244         $args{api_level} ||= 1;
245         $args{stream} ||= 0;
246         $args{remote} ||= 0;
247         $args{package} ||= $app;                
248         $args{server_class} = server_class();
249         $args{api_name} ||= $args{server_class} . '.' . $args{method};
250
251         unless ($args{object_hint}) {
252                 ($args{object_hint} = $args{package}) =~ s/::/_/go;
253         }
254
255         JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
256
257         $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
258
259         __PACKAGE__->register_method(
260                 stream => 0,
261                 api_name => $args{api_name}.'.atomic',
262                 method => 'make_stream_atomic'
263         ) if ($args{stream});
264 }
265
266 sub retrieve_remote_apis {
267         my $method = shift;
268         my $session = OpenSRF::AppSession->create('router');
269         try {
270                 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
271         } catch Error with {
272                 my $e = shift;
273                 $log->debug( "Remote subrequest returned an error:\n". $e );
274                 return undef;
275         } finally {
276                 return undef unless ($session->state == $session->CONNECTED);
277         };
278
279         my $req = $session->request( 'opensrf.router.info.class.list' );
280         my $list = $req->recv;
281
282         if( UNIVERSAL::isa($list,"Error") ) {
283                 throw $list;
284         }
285
286         my $content = $list->content;
287
288         $req->finish;
289         $session->finish;
290         $session->disconnect;
291
292         my %u_list = map { ($_ => 1) } @$content;
293
294         for my $class ( keys %u_list ) {
295                 next if($class eq $server_class);
296                 populate_remote_method_cache($class, $method);
297         }
298 }
299
300 sub populate_remote_method_cache {
301         my $class = shift;
302         my $meth = shift;
303
304         my $session = OpenSRF::AppSession->create($class);
305         try {
306                 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
307
308                 my $call = 'opensrf.system.method.all' unless (defined $meth);
309                 $call = 'opensrf.system.method' if (defined $meth);
310
311                 my $req = $session->request( $call, $meth );
312
313                 while (my $method = $req->recv) {
314                         next if (UNIVERSAL::isa($method, 'Error'));
315
316                         $method = $method->content;
317                         next if ( exists($_METHODS[$$method{api_level}]) &&
318                                 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
319                         $method->{remote} = 1;
320                         bless($method, __PACKAGE__ );
321                         $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
322                 }
323
324                 $req->finish;
325                 $session->finish;
326                 $session->disconnect;
327
328         } catch Error with {
329                 my $e = shift;
330                 $log->debug( "Remote subrequest returned an error:\n". $e );
331                 return undef;
332         };
333 }
334
335 sub method_lookup {             
336         my $self = shift;
337         my $method = shift;
338         my $proto = shift;
339         my $no_recurse = shift || 0;
340         my $no_remote = shift || 0;
341
342         # this instead of " || 1;" above to allow api_level 0
343         $proto = $self->api_level unless (defined $proto);
344
345         my $class = ref($self) || $self;
346
347         $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
348         #$log->debug("Available methods\n".Dumper(\@_METHODS), INTERNAL);
349
350         my $meth;
351         if (__PACKAGE__->thunk) {
352                 for my $p ( reverse(1 .. $proto) ) {
353                         if (exists $_METHODS[$p]{$method}) {
354                                 $meth = $_METHODS[$p]{$method};
355                         }
356                 }
357         } else {
358                 if (exists $_METHODS[$proto]{$method}) {
359                         $meth = $_METHODS[$proto]{$method};
360                 }
361         }
362
363         if (defined $meth) {
364                 $log->debug("Looks like we found [$method]!", DEBUG);
365                 $log->debug("Method object is ".Dumper($meth), INTERNAL);
366                 if($no_remote and $meth->{remote}) {
367                         $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
368                         return undef;
369                 }
370
371         } elsif (!$no_recurse) {
372                 retrieve_remote_apis($method);
373                 $meth = $self->method_lookup($method,$proto,1);
374         }
375
376         return $meth;
377 }
378
379 sub run {
380         my $self = shift;
381         my $req = shift;
382
383         my $resp;
384         my @params = @_;
385
386         if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
387                 $log->debug("Creating a SubRequest object", DEBUG);
388                 unshift @params, $req;
389                 $req = OpenSRF::AppSubrequest->new;
390         } else {
391                 $log->debug("This is a top level request", DEBUG);
392         }
393
394         if (!$self->{remote}) {
395                 my $code ||= \&{$self->{package} . '::' . $self->{method}};
396                 $log->debug("Created coderef [$code] for $$self{package}::$$self{method}",DEBUG);
397                 my $err = undef;
398
399                 try {
400                         $resp = $code->($self, $req, @params);
401
402                 } catch Error with {
403                         my $e = shift;
404                         $err = $e;
405                         warn "Caught Error in Application: $e\n";
406
407                         if( UNIVERSAL::isa($e,"Error")) {
408                                 warn "Exception is:\n " . $e->stringify() . "\n";
409                         }
410
411                         if( ref($self) eq 'HASH') {
412                                 warn $self;
413                                 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$e\n", ERROR);
414                         }
415                 };
416
417                 if($err) {
418                         if(UNIVERSAL::isa($err,"Error")) { 
419                                 throw $err ($err->stringify); 
420                         } else {
421                                 die $err; 
422                         }
423                 }
424
425
426                 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
427
428                 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
429                         $log->debug("A SubRequest object is responding", DEBUG);
430                         $req->respond($resp) if (defined $resp);
431                         $log->debug("... Responding with : " . join(" ",$req->responses), DEBUG);
432                         return $req->responses;
433                 } else {
434                         $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
435                         return $resp;
436                 }
437         } else {
438                 my $session = OpenSRF::AppSession->create($self->{server_class});
439                 try {
440                         $session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
441                         my $remote_req = $session->request( $self->{api_name}, @params );
442                         while (my $remote_resp = $remote_req->recv) {
443                                 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
444                                 if( UNIVERSAL::isa($remote_resp,"Error") ) {
445                                         throw $remote_resp;
446                                 }
447                                 $req->respond( $remote_resp->content );
448                         }
449                         $remote_req->finish();
450                         $session->disconnect();
451                         $session->finish();
452
453                 } catch Error with {
454                         my $e = shift;
455                         $log->debug( "Remote subrequest returned an error:\n". $e );
456                         return undef;
457                 };
458
459                 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
460
461                 return $req->responses;
462         }
463         # huh? how'd we get here...
464         return undef;
465 }
466
467 sub introspect {
468         my $self = shift;
469         my $client = shift;
470         my $method = shift;
471
472         $method = undef if ($self->api_name =~ /all$/o);
473
474         for my $api_level ( reverse(1 .. $#_METHODS) ) {
475                 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
476                         if (!$_METHODS[$api_level]{$api_name}{remote}) {
477                                 if (defined($method)) {
478                                         if ($api_name eq $method) {
479                                                 $client->respond( $_METHODS[$api_level]{$api_name} );
480                                         }
481                                 } else {
482                                         $log->debug( "Returning definition for method [$api_name]", INTERNAL );
483                                         $client->respond( $_METHODS[$api_level]{$api_name} );
484                                         $log->debug( "responed with definition for method [$api_name]", INTERNAL );
485                                 }
486                         }
487                 }
488         }
489
490         return undef;
491 }
492 __PACKAGE__->register_method(
493         stream => 1,
494         method => 'introspect',
495         api_name => 'opensrf.system.method.all'
496 );
497
498 __PACKAGE__->register_method(
499         stream => 1,
500         method => 'introspect',
501         argc => 1,
502         api_name => 'opensrf.system.method'
503 );
504
505 sub make_stream_atomic {
506         my $self = shift;
507         my $req = shift;
508         my @args = @_;
509
510         (my $m_name = $self->api_name) =~ s/\.atomic$//o;
511         my @results = $self->method_lookup($m_name)->run(@args);
512
513         return \@results;
514 }
515
516
517 1;