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