]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/perlmods/OpenSRF/Application.pm
d9388a1f596b58dbb57d4efbb3bcecf29cf6e9ed
[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
214                 my $res = OpenSRF::DomainObject::oilsMethodException->new( 
215                                 status => "Received non-REQUEST message in Application handler");
216                 $session->send('ERROR', $res);
217                 $session->kill_me;
218                 return 1;
219
220         } else {
221                 $log->debug( "Pushing ". $app_msg->toString ." onto queue", INTERNAL );
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;
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".Dumper(\@_METHODS), 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                 retrieve_remote_apis($method);
375                 $meth = $self->method_lookup($method,$proto,1);
376         }
377
378         return $meth;
379 }
380
381 sub run {
382         my $self = shift;
383         my $req = shift;
384
385         my $resp;
386         my @params = @_;
387
388         if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
389                 $log->debug("Creating a SubRequest object", DEBUG);
390                 unshift @params, $req;
391                 $req = OpenSRF::AppSubrequest->new;
392         } else {
393                 $log->debug("This is a top level request", DEBUG);
394         }
395
396         if (!$self->{remote}) {
397                 my $code ||= \&{$self->{package} . '::' . $self->{method}};
398                 $log->debug("Created coderef [$code] for $$self{package}::$$self{method}",DEBUG);
399                 my $err = undef;
400
401                 try {
402                         $resp = $code->($self, $req, @params);
403
404                 } catch Error with {
405                         my $e = shift;
406                         $err = $e;
407                         warn "Caught Error in Application: $e\n";
408
409                         if( UNIVERSAL::isa($e,"Error")) {
410                                 warn "Exception is:\n " . $e->stringify() . "\n";
411                         }
412
413                         if( ref($self) eq 'HASH') {
414                                 warn $self;
415                                 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$e\n", ERROR);
416                         }
417                 };
418
419                 if($err) {
420                         if(UNIVERSAL::isa($err,"Error")) { 
421                                 throw $err ($err->stringify); 
422                         } else {
423                                 die $err; 
424                         }
425                 }
426
427
428                 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
429
430                 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
431                         $log->debug("A SubRequest object is responding", DEBUG);
432                         $req->respond($resp) if (defined $resp);
433                         $log->debug("... Responding with : " . join(" ",$req->responses), DEBUG);
434                         return $req->responses;
435                 } else {
436                         $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
437                         return $resp;
438                 }
439         } else {
440                 my $session = OpenSRF::AppSession->create($self->{server_class});
441                 try {
442                         $session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
443                         my $remote_req = $session->request( $self->{api_name}, @params );
444                         while (my $remote_resp = $remote_req->recv) {
445                                 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
446                                 if( UNIVERSAL::isa($remote_resp,"Error") ) {
447                                         throw $remote_resp;
448                                 }
449                                 $req->respond( $remote_resp->content );
450                         }
451                         $remote_req->finish();
452                         $session->disconnect();
453                         $session->finish();
454
455                 } catch Error with {
456                         my $e = shift;
457                         $log->debug( "Remote subrequest returned an error:\n". $e );
458                         return undef;
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 eq $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
500 __PACKAGE__->register_method(
501         stream => 1,
502         method => 'introspect',
503         argc => 1,
504         api_name => 'opensrf.system.method'
505 );
506
507 sub make_stream_atomic {
508         my $self = shift;
509         my $req = shift;
510         my @args = @_;
511
512         (my $m_name = $self->api_name) =~ s/\.atomic$//o;
513         my @results = $self->method_lookup($m_name)->run(@args);
514
515         return \@results;
516 }
517
518
519 1;