]> git.evergreen-ils.org Git - Evergreen.git/blob - OpenSRF/src/perlmods/OpenSRF/Application.pm
adding MethodException backtrace
[Evergreen.git] / OpenSRF / 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
156                                 my $stack = "-=-=-=-=-=- Stack Backtrace (5) -=-=-=-=-=-\n";
157                                 for my $lvl ( 1 .. 5 ) {
158                                         my ($package, $filename, $line, $subroutine, $hasargs,
159                                             $wantarray, $evaltext, $is_require, $hints, $bitmask) = caller($lvl);
160                                         $stack .= "PKG[$package]|FILE[$filename]|LINE[$line]|SUB[$subroutine]\n";
161                                 }
162                                 
163                                 $session->status(
164                                         OpenSRF::DomainObject::oilsMethodException->new(
165                                                         statusCode      => STATUS_INTERNALSERVERERROR(),
166                                                         status          => " *** Call to [$method_name] failed for session ".
167                                                                            "[$sess_id], thread trace ".
168                                                                            "[".$appreq->threadTrace."]:\n$e\n\n$stack"
169                                         )
170                                 );
171                         };
172
173
174
175                         # ----------------------------------------------
176
177
178                         # XXX may need this later
179                         # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
180
181                         $in_request--;
182
183                         $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
184
185                         # cycle through queued requests
186                         while( my $aref = shift @pending_requests ) {
187                                 $in_request++;
188                                 my $resp;
189                                 try {
190                                         my $start = time;
191                                         my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
192                                         my $time = sprintf '%.3f', time - $start;
193                                         $log->debug( "Method duration for {[".$aref->[2]->api_name." -> ".join(', ',@{$aref->[1]}).'}:  '.$time, DEBUG );
194
195                                         $appreq = $aref->[0];   
196                                         if( ref( $response ) ) {
197                                                 #$log->debug( "Calling respond_complete: ". $response->toString(), INTERNAL );
198                                                 $appreq->respond_complete( $response );
199                                         } else {
200                                                 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
201                                                                         statusCode => STATUS_COMPLETE(),
202                                                                         status => 'Request Complete' ) );
203                                         }
204                                         $log->debug( "Executed: " . $appreq->threadTrace, DEBUG );
205                                 } catch Error with {
206                                         my $e = shift;
207                                         if(UNIVERSAL::isa($e,"Error")) {
208                                                 $e = $e->stringify();
209                                         }
210                                         $session->status(
211                                                 OpenSRF::DomainObject::oilsMethodException->new(
212                                                                 statusCode => STATUS_INTERNALSERVERERROR(),
213                                                                 status => "Call to [".$aref->[2]->api_name."] faild:  $e"
214                                                 )
215                                         );
216                                 };
217                                 $in_request--;
218                         }
219
220                         return 1;
221                 } 
222
223                 my $res = OpenSRF::DomainObject::oilsMethodException->new( 
224                                 status => "Received non-REQUEST message in Application handler");
225                 $session->send('ERROR', $res);
226                 $session->kill_me;
227                 return 1;
228
229         } else {
230                 $log->debug( "Pushing ". $app_msg->toString ." onto queue", INTERNAL );
231                 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
232         }
233
234         $session->last_message_type('');
235         $session->last_message_api_level('');
236
237         return 1;
238 }
239
240 sub is_registered {
241         my $self = shift;
242         my $api_name = shift;
243         my $api_level = shift || 1;
244         return exists($_METHODS[$api_level]{$api_name});
245 }
246
247 sub register_method {
248         my $self = shift;
249         my $app = ref($self) || $self;
250         my %args = @_;
251
252
253         throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
254
255         $args{api_level} = 1 unless(defined($args{api_level}));
256         $args{stream} ||= 0;
257         $args{remote} ||= 0;
258         $args{package} ||= $app;                
259         $args{server_class} = server_class();
260         $args{api_name} ||= $args{server_class} . '.' . $args{method};
261
262         unless ($args{object_hint}) {
263                 ($args{object_hint} = $args{package}) =~ s/::/_/go;
264         }
265
266         JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
267
268         $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
269
270         __PACKAGE__->register_method(
271                 stream => 0,
272                 api_name => $args{api_name}.'.atomic',
273                 method => 'make_stream_atomic'
274         ) if ($args{stream});
275 }
276
277 sub retrieve_remote_apis {
278         my $method = shift;
279         my $session = OpenSRF::AppSession->create('router');
280         try {
281                 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
282         } catch Error with {
283                 my $e = shift;
284                 $log->debug( "Remote subrequest returned an error:\n". $e );
285                 return undef;
286         } finally {
287                 return undef unless ($session->state == $session->CONNECTED);
288         };
289
290         my $req = $session->request( 'opensrf.router.info.class.list' );
291         my $list = $req->recv;
292
293         if( UNIVERSAL::isa($list,"Error") ) {
294                 throw $list;
295         }
296
297         my $content = $list->content;
298
299         $req->finish;
300         $session->finish;
301         $session->disconnect;
302
303         my %u_list = map { ($_ => 1) } @$content;
304
305         for my $class ( keys %u_list ) {
306                 next if($class eq $server_class);
307                 populate_remote_method_cache($class, $method);
308         }
309 }
310
311 sub populate_remote_method_cache {
312         my $class = shift;
313         my $meth = shift;
314
315         my $session = OpenSRF::AppSession->create($class);
316         try {
317                 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
318
319                 my $call = 'opensrf.system.method.all' unless (defined $meth);
320                 $call = 'opensrf.system.method' if (defined $meth);
321
322                 my $req = $session->request( $call, $meth );
323
324                 while (my $method = $req->recv) {
325                         next if (UNIVERSAL::isa($method, 'Error'));
326
327                         $method = $method->content;
328                         next if ( exists($_METHODS[$$method{api_level}]) &&
329                                 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
330                         $method->{remote} = 1;
331                         bless($method, __PACKAGE__ );
332                         $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
333                 }
334
335                 $req->finish;
336                 $session->finish;
337                 $session->disconnect;
338
339         } catch Error with {
340                 my $e = shift;
341                 $log->debug( "Remote subrequest returned an error:\n". $e );
342                 return undef;
343         };
344 }
345
346 sub method_lookup {             
347         my $self = shift;
348         my $method = shift;
349         my $proto = shift;
350         my $no_recurse = shift || 0;
351         my $no_remote = shift || 0;
352
353         # this instead of " || 1;" above to allow api_level 0
354         $proto = $self->api_level unless (defined $proto);
355
356         my $class = ref($self) || $self;
357
358         $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
359         #$log->debug("Available methods\n".Dumper(\@_METHODS), INTERNAL);
360
361         my $meth;
362         if (__PACKAGE__->thunk) {
363                 for my $p ( reverse(1 .. $proto) ) {
364                         if (exists $_METHODS[$p]{$method}) {
365                                 $meth = $_METHODS[$p]{$method};
366                         }
367                 }
368         } else {
369                 if (exists $_METHODS[$proto]{$method}) {
370                         $meth = $_METHODS[$proto]{$method};
371                 }
372         }
373
374         if (defined $meth) {
375                 $log->debug("Looks like we found [$method]!", DEBUG);
376                 $log->debug("Method object is ".Dumper($meth), INTERNAL);
377                 if($no_remote and $meth->{remote}) {
378                         $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
379                         return undef;
380                 }
381
382         } elsif (!$no_recurse) {
383                 retrieve_remote_apis($method);
384                 $meth = $self->method_lookup($method,$proto,1);
385         }
386
387         return $meth;
388 }
389
390 sub run {
391         my $self = shift;
392         my $req = shift;
393
394         my $resp;
395         my @params = @_;
396
397         if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
398                 $log->debug("Creating a SubRequest object", DEBUG);
399                 unshift @params, $req;
400                 $req = OpenSRF::AppSubrequest->new;
401         } else {
402                 $log->debug("This is a top level request", DEBUG);
403         }
404
405         if (!$self->{remote}) {
406                 my $code ||= \&{$self->{package} . '::' . $self->{method}};
407                 $log->debug("Created coderef [$code] for $$self{package}::$$self{method}",DEBUG);
408                 my $err = undef;
409
410                 try {
411                         $resp = $code->($self, $req, @params);
412
413                 } catch Error with {
414                         my $e = shift;
415                         $err = $e;
416                         warn "Caught Error in Application: $e\n";
417
418                         if( UNIVERSAL::isa($e,"Error")) {
419                                 warn "Exception is:\n " . $e->stringify() . "\n";
420                         }
421
422                         if( ref($self) eq 'HASH') {
423                                 warn $self;
424                                 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$e\n", ERROR);
425                         }
426                 };
427
428                 if($err) {
429                         if(UNIVERSAL::isa($err,"Error")) { 
430                                 throw $err ($err->stringify); 
431                         } else {
432                                 die $err; 
433                         }
434                 }
435
436
437                 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
438
439                 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
440                         $log->debug("A SubRequest object is responding", DEBUG);
441                         $req->respond($resp) if (defined $resp);
442                         $log->debug("... Responding with : " . join(" ",$req->responses), DEBUG);
443                         return $req->responses;
444                 } else {
445                         $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
446                         return $resp;
447                 }
448         } else {
449                 my $session = OpenSRF::AppSession->create($self->{server_class});
450                 try {
451                         $session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
452                         my $remote_req = $session->request( $self->{api_name}, @params );
453                         while (my $remote_resp = $remote_req->recv) {
454                                 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
455                                 if( UNIVERSAL::isa($remote_resp,"Error") ) {
456                                         throw $remote_resp;
457                                 }
458                                 $req->respond( $remote_resp->content );
459                         }
460                         $remote_req->finish();
461                         $session->disconnect();
462                         $session->finish();
463
464                 } catch Error with {
465                         my $e = shift;
466                         $log->debug( "Remote subrequest returned an error:\n". $e );
467                         return undef;
468                 };
469
470                 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
471
472                 return $req->responses;
473         }
474         # huh? how'd we get here...
475         return undef;
476 }
477
478 sub introspect {
479         my $self = shift;
480         my $client = shift;
481         my $method = shift;
482
483         $method = undef if ($self->api_name =~ /all$/o);
484
485         for my $api_level ( reverse(1 .. $#_METHODS) ) {
486                 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
487                         if (!$_METHODS[$api_level]{$api_name}{remote}) {
488                                 if (defined($method)) {
489                                         if ($api_name =~ $method) {
490                                                 $client->respond( $_METHODS[$api_level]{$api_name} );
491                                         }
492                                 } else {
493                                         $log->debug( "Returning definition for method [$api_name]", INTERNAL );
494                                         $client->respond( $_METHODS[$api_level]{$api_name} );
495                                         $log->debug( "responed with definition for method [$api_name]", INTERNAL );
496                                 }
497                         }
498                 }
499         }
500
501         return undef;
502 }
503 __PACKAGE__->register_method(
504         stream => 1,
505         method => 'introspect',
506         api_name => 'opensrf.system.method.all'
507 );
508
509 __PACKAGE__->register_method(
510         stream => 1,
511         method => 'introspect',
512         argc => 1,
513         api_name => 'opensrf.system.method'
514 );
515
516 sub make_stream_atomic {
517         my $self = shift;
518         my $req = shift;
519         my @args = @_;
520
521         (my $m_name = $self->api_name) =~ s/\.atomic$//o;
522         my @results = $self->method_lookup($m_name)->run(@args);
523
524         return \@results;
525 }
526
527
528 1;