]> git.evergreen-ils.org Git - Evergreen.git/blob - OpenSRF/src/perlmods/OpenSRF/Application.pm
allow method lookup for a single method. open-ils.storage takes 10s without this...
[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                         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 -> ".join(', ', @args)."}", INTERNAL );
133
134                         my $resp;
135                         try {
136                                 my $start = time();
137                                 $resp = $coderef->run( $appreq, @args); 
138                                 my $time = sprintf '%.3f', time() - $start;
139                                 $log->debug( "Method duration for {$method_name -> ".join(', ', @args)."}:  ". $time, DEBUG );
140                                 if( defined( $resp ) ) {
141                                         #$log->debug( "Calling respond_complete: ". $resp->toString(), INTERNAL );
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                                 if(UNIVERSAL::isa($e,"Error")) {
151                                         $e = $e->stringify();
152                                 } 
153                                 my $sess_id = $session->session_id;
154                                 $session->status(
155                                         OpenSRF::DomainObject::oilsMethodException->new(
156                                                         statusCode      => STATUS_INTERNALSERVERERROR(),
157                                                         status          => " *** Call to [$method_name] failed for session ".
158                                                                            "[$sess_id], thread trace [".$appreq->threadTrace."]:\n$e"
159                                         )
160                                 );
161                         };
162
163
164
165                         # ----------------------------------------------
166
167
168                         # XXX may need this later
169                         # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
170
171                         $in_request--;
172
173                         $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
174
175                         # cycle through queued requests
176                         while( my $aref = shift @pending_requests ) {
177                                 $in_request++;
178                                 my $resp;
179                                 try {
180                                         my $start = time;
181                                         my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
182                                         my $time = sprintf '%.3f', time - $start;
183                                         $log->debug( "Method duration for {[".$aref->[2]->api_name." -> ".join(', ',@{$aref->[1]}).'}:  '.$time, DEBUG );
184
185                                         $appreq = $aref->[0];   
186                                         if( ref( $response ) ) {
187                                                 #$log->debug( "Calling respond_complete: ". $response->toString(), INTERNAL );
188                                                 $appreq->respond_complete( $response );
189                                         } else {
190                                                 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
191                                                                         statusCode => STATUS_COMPLETE(),
192                                                                         status => 'Request Complete' ) );
193                                         }
194                                         $log->debug( "Executed: " . $appreq->threadTrace, DEBUG );
195                                 } catch Error with {
196                                         my $e = shift;
197                                         if(UNIVERSAL::isa($e,"Error")) {
198                                                 $e = $e->stringify();
199                                         }
200                                         $session->status(
201                                                 OpenSRF::DomainObject::oilsMethodException->new(
202                                                                 statusCode => STATUS_INTERNALSERVERERROR(),
203                                                                 status => "Call to [".$aref->[2]->api_name."] faild:  $e"
204                                                 )
205                                         );
206                                 };
207                                 $in_request--;
208                         }
209
210                         return 1;
211                 } 
212                 my $res = OpenSRF::DomainObject::oilsMethodException->new;
213                 $session->send('ERROR', $res);
214                 $session->kill_me;
215                 return 1;
216
217         } else {
218                 $log->debug( "Pushing ". $app_msg->toString ." onto queue", INTERNAL );
219                 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
220         }
221
222         $session->last_message_type('');
223         $session->last_message_api_level('');
224
225         return 1;
226 }
227
228 sub is_registered {
229         my $self = shift;
230         my $api_name = shift;
231         my $api_level = shift || 1;
232         return exists($_METHODS[$api_level]{$api_name});
233 }
234
235 sub register_method {
236         my $self = shift;
237         my $app = ref($self) || $self;
238         my %args = @_;
239
240
241         throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
242
243         $args{api_level} ||= 1;
244         $args{stream} ||= 0;
245         $args{remote} ||= 0;
246         $args{package} ||= $app;                
247         $args{server_class} = server_class();
248         $args{api_name} ||= $args{server_class} . '.' . $args{method};
249
250         unless ($args{object_hint}) {
251                 ($args{object_hint} = $args{package}) =~ s/::/_/go;
252         }
253
254         JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
255
256         $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
257
258         __PACKAGE__->register_method(
259                 stream => 0,
260                 api_name => $args{api_name}.'.atomic',
261                 method => 'make_stream_atomic'
262         ) if ($args{stream});
263 }
264
265 sub retrieve_remote_apis {
266         my $method = shift;
267         my $session = OpenSRF::AppSession->create('router');
268         try {
269                 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
270         } catch Error with {
271                 my $e = shift;
272                 $log->debug( "Remote subrequest returned an error:\n". $e );
273                 return undef;
274         } finally {
275                 return undef unless ($session->state == $session->CONNECTED);
276         };
277
278         my $req = $session->request( 'opensrf.router.info.class.list' );
279         my $list = $req->recv;
280
281         if( UNIVERSAL::isa($list,"Error") ) {
282                 throw $list;
283         }
284
285         my $content = $list->content;
286
287         $req->finish;
288         $session->finish;
289         $session->disconnect;
290
291         my %u_list = map { ($_ => 1) } @$content;
292
293         for my $class ( keys %u_list ) {
294                 next if($class eq $server_class);
295                 populate_remote_method_cache($class, $method);
296         }
297 }
298
299 sub populate_remote_method_cache {
300         my $class = shift;
301         my $meth = shift;
302
303         my $session = OpenSRF::AppSession->create($class);
304         try {
305                 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
306
307                 my $call = 'opensrf.system.method.all' unless (defined $meth);
308                 $call = 'opensrf.system.method' if (defined $meth);
309
310                 my $req = $session->request( $call, $meth );
311
312                 while (my $method = $req->recv) {
313                         next if (UNIVERSAL::isa($method, 'Error'));
314
315                         $method = $method->content;
316                         next if ( exists($_METHODS[$$method{api_level}]) &&
317                                 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
318                         $method->{remote} = 1;
319                         bless($method, __PACKAGE__ );
320                         $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
321                 }
322
323                 $req->finish;
324                 $session->finish;
325                 $session->disconnect;
326
327         } catch Error with {
328                 my $e = shift;
329                 $log->debug( "Remote subrequest returned an error:\n". $e );
330                 return undef;
331         };
332 }
333
334 sub method_lookup {             
335         my $self = shift;
336         my $method = shift;
337         my $proto = shift;
338         my $no_recurse = shift || 0;
339         my $no_remote = shift || 0;
340
341         # this instead of " || 1;" above to allow api_level 0
342         $proto = $self->api_level unless (defined $proto);
343
344         my $class = ref($self) || $self;
345
346         $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
347         #$log->debug("Available methods\n".Dumper(\@_METHODS), INTERNAL);
348
349         my $meth;
350         if (__PACKAGE__->thunk) {
351                 for my $p ( reverse(1 .. $proto) ) {
352                         if (exists $_METHODS[$p]{$method}) {
353                                 $meth = $_METHODS[$p]{$method};
354                         }
355                 }
356         } else {
357                 if (exists $_METHODS[$proto]{$method}) {
358                         $meth = $_METHODS[$proto]{$method};
359                 }
360         }
361
362         if (defined $meth) {
363                 $log->debug("Looks like we found [$method]!", DEBUG);
364                 $log->debug("Method object is ".Dumper($meth), INTERNAL);
365                 if($no_remote and $meth->{remote}) {
366                         $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
367                         return undef;
368                 }
369
370         } elsif (!$no_recurse) {
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                         $session->disconnect();
450                         $session->finish();
451
452                 } catch Error with {
453                         my $e = shift;
454                         $log->debug( "Remote subrequest returned an error:\n". $e );
455                         return undef;
456                 };
457
458                 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
459
460                 return $req->responses;
461         }
462         # huh? how'd we get here...
463         return undef;
464 }
465
466 sub introspect {
467         my $self = shift;
468         my $client = shift;
469         my $method = shift;
470
471         $method = undef if ($self->api_name =~ /all$/o);
472
473         for my $api_level ( reverse(1 .. $#_METHODS) ) {
474                 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
475                         if (!$_METHODS[$api_level]{$api_name}{remote}) {
476                                 if (defined($method)) {
477                                         if ($api_name eq $method) {
478                                                 $client->respond( $_METHODS[$api_level]{$api_name} );
479                                         }
480                                 } else {
481                                         $log->debug( "Returning definition for method [$api_name]", INTERNAL );
482                                         $client->respond( $_METHODS[$api_level]{$api_name} );
483                                         $log->debug( "responed with definition for method [$api_name]", INTERNAL );
484                                 }
485                         }
486                 }
487         }
488
489         return undef;
490 }
491 __PACKAGE__->register_method(
492         stream => 1,
493         method => 'introspect',
494         api_name => 'opensrf.system.method.all'
495 );
496
497 __PACKAGE__->register_method(
498         stream => 1,
499         method => 'introspect',
500         argc => 1,
501         api_name => 'opensrf.system.method'
502 );
503
504 sub make_stream_atomic {
505         my $self = shift;
506         my $req = shift;
507         my @args = @_;
508
509         (my $m_name = $self->api_name) =~ s/\.atomic$//o;
510         my @results = $self->method_lookup($m_name)->run(@args);
511
512         return \@results;
513 }
514
515
516 1;