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