]> git.evergreen-ils.org Git - Evergreen.git/blob - OpenSRF/src/perlmods/OpenSRF/Application.pm
99346c36f63b62ff245bc62f348f4e8debc945ff
[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                                                 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}", INTERNAL );
132
133                         my $resp;
134                         try {
135                                 my $start = time();
136                                 warn "About to run...\n";
137                                 $resp = $coderef->run( $appreq, @args); 
138                                 warn "Done running...\n";
139                                 my $time = sprintf '%.3f', time() - $start;
140                                 $log->debug( "Method duration for {$method_name}:  ". $time, INFO );
141                                 if( defined( $resp ) ) {
142                                         $appreq->respond_complete( $resp );
143                                 } else {
144                                         $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
145                                                                 statusCode => STATUS_COMPLETE(),
146                                                                 status => 'Request Complete' ) );
147                                 }
148                         } catch Error with {
149                                 my $e = shift;
150                                 warn "Caught error from 'run' method: $e\n";
151
152                                 if(UNIVERSAL::isa($e,"Error")) {
153                                         $e = $e->stringify();
154                                 } 
155                                 my $sess_id = $session->session_id;
156                                 $session->status(
157                                         OpenSRF::DomainObject::oilsMethodException->new(
158                                                         statusCode      => STATUS_INTERNALSERVERERROR(),
159                                                         status          => " *** Call to [$method_name] failed for session ".
160                                                                            "[$sess_id], thread trace ".
161                                                                            "[".$appreq->threadTrace."]:\n$e\n"
162                                         )
163                                 );
164                         };
165
166
167
168                         # ----------------------------------------------
169
170
171                         # XXX may need this later
172                         # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
173
174                         $in_request--;
175
176                         $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
177
178                         # cycle through queued requests
179                         while( my $aref = shift @pending_requests ) {
180                                 $in_request++;
181                                 my $resp;
182                                 try {
183                                         my $start = time;
184                                         my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
185                                         my $time = sprintf '%.3f', time - $start;
186                                         $log->debug( "Method duration for {[".$aref->[2]->api_name." -> ".join(', ',@{$aref->[1]}).'}:  '.$time, DEBUG );
187
188                                         $appreq = $aref->[0];   
189                                         if( ref( $response ) ) {
190                                                 $appreq->respond_complete( $response );
191                                         } else {
192                                                 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
193                                                                         statusCode => STATUS_COMPLETE(),
194                                                                         status => 'Request Complete' ) );
195                                         }
196                                         $log->debug( "Executed: " . $appreq->threadTrace, DEBUG );
197                                 } catch Error with {
198                                         my $e = shift;
199                                         if(UNIVERSAL::isa($e,"Error")) {
200                                                 $e = $e->stringify();
201                                         }
202                                         $session->status(
203                                                 OpenSRF::DomainObject::oilsMethodException->new(
204                                                                 statusCode => STATUS_INTERNALSERVERERROR(),
205                                                                 status => "Call to [".$aref->[2]->api_name."] faild:  $e"
206                                                 )
207                                         );
208                                 };
209                                 $in_request--;
210                         }
211
212                         return 1;
213                 } 
214
215                 my $res = OpenSRF::DomainObject::oilsMethodException->new( 
216                                 status => "Received non-REQUEST message in Application handler");
217                 $session->send('ERROR', $res);
218                 $session->kill_me;
219                 return 1;
220
221         } else {
222                 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
223         }
224
225         $session->last_message_type('');
226         $session->last_message_api_level('');
227
228         return 1;
229 }
230
231 sub is_registered {
232         my $self = shift;
233         my $api_name = shift;
234         my $api_level = shift || 1;
235         return exists($_METHODS[$api_level]{$api_name});
236 }
237
238 sub register_method {
239         my $self = shift;
240         my $app = ref($self) || $self;
241         my %args = @_;
242
243
244         throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
245
246         $args{api_level} = 1 unless(defined($args{api_level}));
247         $args{stream} ||= 0;
248         $args{remote} ||= 0;
249         $args{package} ||= $app;                
250         $args{server_class} = server_class();
251         $args{api_name} ||= $args{server_class} . '.' . $args{method};
252
253         unless ($args{object_hint}) {
254                 ($args{object_hint} = $args{package}) =~ s/::/_/go;
255         }
256
257         JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
258
259         $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
260
261         __PACKAGE__->register_method(
262                 stream => 0,
263                 api_name => $args{api_name}.'.atomic',
264                 method => 'make_stream_atomic'
265         ) if ($args{stream});
266 }
267
268 sub retrieve_remote_apis {
269         my $method = shift;
270         my $session = OpenSRF::AppSession->create('router');
271         try {
272                 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
273         } catch Error with {
274                 my $e = shift;
275                 $log->debug( "Remote subrequest returned an error:\n". $e );
276                 return undef;
277         } finally {
278                 return undef unless ($session->state == $session->CONNECTED);
279         };
280
281         my $req = $session->request( 'opensrf.router.info.class.list' );
282         my $list = $req->recv;
283
284         if( UNIVERSAL::isa($list,"Error") ) {
285                 throw $list;
286         }
287
288         my $content = $list->content;
289
290         $req->finish;
291         $session->finish;
292         $session->disconnect;
293
294         my %u_list = map { ($_ => 1) } @$content;
295
296         for my $class ( keys %u_list ) {
297                 next if($class eq $server_class);
298                 populate_remote_method_cache($class, $method);
299         }
300 }
301
302 sub populate_remote_method_cache {
303         my $class = shift;
304         my $meth = shift;
305
306         my $session = OpenSRF::AppSession->create($class);
307         try {
308                 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
309
310                 my $call = 'opensrf.system.method.all' unless (defined $meth);
311                 $call = 'opensrf.system.method' if (defined $meth);
312
313                 my $req = $session->request( $call, $meth );
314
315                 while (my $method = $req->recv) {
316                         next if (UNIVERSAL::isa($method, 'Error'));
317
318                         $method = $method->content;
319                         next if ( exists($_METHODS[$$method{api_level}]) &&
320                                 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
321                         $method->{remote} = 1;
322                         bless($method, __PACKAGE__ );
323                         $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
324                 }
325
326                 $req->finish;
327                 $session->finish;
328                 $session->disconnect;
329
330         } catch Error with {
331                 my $e = shift;
332                 $log->debug( "Remote subrequest returned an error:\n". $e );
333                 return undef;
334         };
335 }
336
337 sub method_lookup {             
338         my $self = shift;
339         my $method = shift;
340         my $proto = shift;
341         my $no_recurse = shift || 0;
342         my $no_remote = shift || 0;
343
344         # this instead of " || 1;" above to allow api_level 0
345         $proto = $self->api_level unless (defined $proto);
346
347         my $class = ref($self) || $self;
348
349         $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
350         $log->debug("Available methods\n\t".join("\n\t", keys %{ $_METHODS[$proto] }), INTERNAL);
351
352         my $meth;
353         if (__PACKAGE__->thunk) {
354                 for my $p ( reverse(1 .. $proto) ) {
355                         if (exists $_METHODS[$p]{$method}) {
356                                 $meth = $_METHODS[$p]{$method};
357                         }
358                 }
359         } else {
360                 if (exists $_METHODS[$proto]{$method}) {
361                         $meth = $_METHODS[$proto]{$method};
362                 }
363         }
364
365         if (defined $meth) {
366                 $log->debug("Looks like we found [$method]!", DEBUG);
367                 $log->debug("Method object is ".Dumper($meth), INTERNAL);
368                 if($no_remote and $meth->{remote}) {
369                         $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
370                         return undef;
371                 }
372
373         } elsif (!$no_recurse) {
374                 $log->debug("We didn't find [$method], asking everyone else.", DEBUG);
375                 retrieve_remote_apis($method);
376                 $meth = $self->method_lookup($method,$proto,1);
377         }
378
379         return $meth;
380 }
381
382 sub run {
383         my $self = shift;
384         my $req = shift;
385
386         my $resp;
387         my @params = @_;
388
389         if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
390                 $log->debug("Creating a SubRequest object", DEBUG);
391                 unshift @params, $req;
392                 $req = OpenSRF::AppSubrequest->new;
393         } else {
394                 $log->debug("This is a top level request", DEBUG);
395         }
396
397         if (!$self->{remote}) {
398                 my $code ||= \&{$self->{package} . '::' . $self->{method}};
399                 $log->debug("Created coderef [$code] for $$self{package}::$$self{method}",DEBUG);
400                 my $err = undef;
401
402                 try {
403                         $resp = $code->($self, $req, @params);
404
405                 } catch Error with {
406                         my $e = shift;
407                         $err = $e;
408                         warn "Method 'run' catching error: $e\n";
409
410                         if( ref($self) eq 'HASH') {
411                                 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$e\n", ERROR);
412                         }
413                 };
414
415                 if($err) {
416                         if(UNIVERSAL::isa($err,"Error")) { 
417                                 warn "Throwing from method run:\n$err\n------------------\n";
418                                 throw $err;
419                         } else {
420                                 die $err->stringify; 
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;