]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/perlmods/OpenSRF/Application.pm
2e15519be3c1cc7f97566a6012b04615c580f81e
[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                         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                                 $e = $e->{-text} || $e->message if (ref $e);
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 [".$appreq->threadTrace."]:\n$e"
157                                         )
158                                 );
159                         };
160
161
162
163                         # ----------------------------------------------
164
165
166                         # XXX may need this later
167                         # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
168
169                         $in_request--;
170
171                         $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
172
173                         # cycle through queued requests
174                         while( my $aref = shift @pending_requests ) {
175                                 $in_request++;
176                                 my $resp;
177                                 try {
178                                         my $start = time;
179                                         my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
180                                         my $time = sprintf '%.3f', time - $start;
181                                         $log->debug( "Method duration for {[".$aref->[2]->api_name." -> ".join(', ',@{$aref->[1]}).'}:  '.$time, DEBUG );
182
183                                         $appreq = $aref->[0];   
184                                         if( ref( $response ) ) {
185                                                 $log->debug( "Calling respond_complete: ". $response->toString(), INTERNAL );
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                                         $session->status(
196                                                 OpenSRF::DomainObject::oilsMethodException->new(
197                                                                 statusCode => STATUS_INTERNALSERVERERROR(),
198                                                                 status => "Call to [".$aref->[2]->api_name."] faild:  ".$e->{-text}
199                                                 )
200                                         );
201                                 };
202                                 $in_request--;
203                         }
204
205                         return 1;
206                 } 
207                 my $res = OpenSRF::DomainObject::oilsMethodException->new;
208                 $session->send('ERROR', $res);
209                 $session->kill_me;
210                 return 1;
211
212         } else {
213                 $log->debug( "Pushing ". $app_msg->toString ." onto queue", INTERNAL );
214                 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
215         }
216
217         $session->last_message_type('');
218         $session->last_message_api_level('');
219
220         return 1;
221 }
222
223 sub is_registered {
224         my $self = shift;
225         my $api_name = shift;
226         my $api_level = shift || 1;
227         return exists($_METHODS[$api_level]{$api_name});
228 }
229
230 sub register_method {
231         my $self = shift;
232         my $app = ref($self) || $self;
233         my %args = @_;
234
235
236         throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
237
238         $args{api_level} ||= 1;
239         $args{stream} ||= 0;
240         $args{remote} ||= 0;
241         $args{package} = $app;                
242         $args{server_class} = server_class();
243         $args{api_name} ||= $args{server_class} . '.' . $args{method};
244
245         unless ($args{object_hint}) {
246                 ($args{object_hint} = $args{package}) =~ s/::/_/go;
247         }
248
249         JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
250
251         $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
252
253         __PACKAGE__->register_method(
254                 stream => 0,
255                 api_name => $args{api_name}.'.atomic',
256                 method => 'make_stream_atomic'
257         ) if ($args{stream});
258 }
259
260 sub retrieve_remote_apis {
261         my $session = OpenSRF::AppSession->create('router');
262         try {
263                 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
264         } catch Error with {
265                 my $e = shift;
266                 $log->debug( "Remote subrequest returned an error:\n". $e );
267                 return undef;
268         } finally {
269                 return undef unless ($session->state == $session->CONNECTED);
270         };
271
272         my $req = $session->request( 'opensrf.router.info.class.list' );
273         my $list = $req->recv;
274
275         if( UNIVERSAL::isa($list,"Error") ) {
276                 throw $list;
277         }
278
279         my $content = $list->content;
280
281         $req->finish;
282         $session->finish;
283         $session->disconnect;
284
285         my %u_list = map { ($_ => 1) } @$content;
286
287         for my $class ( keys %u_list ) {
288                 next if($class eq $server_class);
289                 populate_remote_method_cache($class);
290         }
291 }
292
293 sub populate_remote_method_cache {
294         my $class = shift;
295
296         my $session = OpenSRF::AppSession->create($class);
297         try {
298                 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
299
300                 my $req = $session->request( 'opensrf.system.method.all' );
301
302                 while (my $method = $req->recv) {
303                         next if (UNIVERSAL::isa($method, 'Error'));
304
305                         $method = $method->content;
306                         next if ( exists($_METHODS[$$method{api_level}]) &&
307                                 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
308                         $method->{remote} = 1;
309                         bless($method, __PACKAGE__ );
310                         $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
311                 }
312
313                 $req->finish;
314                 $session->finish;
315                 $session->disconnect;
316
317         } catch Error with {
318                 my $e = shift;
319                 $log->debug( "Remote subrequest returned an error:\n". $e );
320                 return undef;
321         };
322 }
323
324 sub method_lookup {             
325         my $self = shift;
326         my $method = shift;
327         my $proto = shift;
328         my $no_recurse = shift || 0;
329         my $no_remote = shift || 0;
330
331         # this instead of " || 1;" above to allow api_level 0
332         $proto = $self->api_level unless (defined $proto);
333
334         my $class = ref($self) || $self;
335
336         $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
337         #$log->debug("Available methods\n".Dumper(\@_METHODS), INTERNAL);
338
339         my $meth;
340         if (__PACKAGE__->thunk) {
341                 for my $p ( reverse(1 .. $proto) ) {
342                         if (exists $_METHODS[$p]{$method}) {
343                                 $meth = $_METHODS[$p]{$method};
344                         }
345                 }
346         } else {
347                 if (exists $_METHODS[$proto]{$method}) {
348                         $meth = $_METHODS[$proto]{$method};
349                 }
350         }
351
352         if (defined $meth) {
353                 $log->debug("Looks like we found [$method]!", DEBUG);
354                 $log->debug("Method object is ".Dumper($meth), INTERNAL);
355                 if($no_remote and $meth->{remote}) {
356                         $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
357                         return undef;
358                 }
359
360         } elsif (!$no_recurse) {
361                 retrieve_remote_apis();
362                 $meth = $self->method_lookup($method,$proto,1);
363         }
364
365         return $meth;
366 }
367
368 sub run {
369         my $self = shift;
370         my $req = shift;
371
372         my $resp;
373         my @params = @_;
374
375         if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
376                 $log->debug("Creating a SubRequest object", DEBUG);
377                 unshift @params, $req;
378                 $req = OpenSRF::AppSubrequest->new;
379         } else {
380                 $log->debug("This is a top level request", DEBUG);
381         }
382
383         if (!$self->{remote}) {
384                 my $code ||= \&{$self->{package} . '::' . $self->{method}};
385                 $log->debug("Created coderef [$code] for $$self{package}::$$self{method}",DEBUG);
386                 try {
387                         $resp = $code->($self, $req, @params);
388                 } catch Error with {
389                         my $e = shift;
390                         $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$e\n".Carp::longmess(), ERROR);
391                         die $e;
392                 };
393
394                 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
395
396                 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
397                         $log->debug("A SubRequest object is responding", DEBUG);
398                         $req->respond($resp) if (defined $resp);
399                         $log->debug("... Responding with : " . join(" ",$req->responses), DEBUG);
400                         return $req->responses;
401                 } else {
402                         $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
403                         return $resp;
404                 }
405         } else {
406                 my $session = OpenSRF::AppSession->create($self->{server_class});
407                 try {
408                         $session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
409                         my $remote_req = $session->request( $self->{api_name}, @params );
410                         while (my $remote_resp = $remote_req->recv) {
411                                 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
412                                 if( UNIVERSAL::isa($remote_resp,"Error") ) {
413                                         throw $remote_resp;
414                                 }
415                                 $req->respond( $remote_resp->content );
416                         }
417                         $remote_req->finish();
418                         $session->finish();
419
420                 } catch Error with {
421                         my $e = shift;
422                         $log->debug( "Remote subrequest returned an error:\n". $e );
423                         return undef;
424                 };
425
426                 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
427
428                 return $req->responses;
429         }
430         # huh? how'd we get here...
431         return undef;
432 }
433
434 sub introspect {
435         my $self = shift;
436         my $client = shift;
437         my $method = shift;
438
439         $method = undef if ($self->api_name =~ /all$/o);
440
441         for my $api_level ( reverse(1 .. $#_METHODS) ) {
442                 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
443                         if (!$_METHODS[$api_level]{$api_name}{remote}) {
444                                 if (defined($method)) {
445                                         if ($api_name eq $method) {
446                                                 $client->respond( $_METHODS[$api_level]{$api_name} );
447                                         }
448                                 } else {
449                                         $log->debug( "Returning definition for method [$api_name]", INTERNAL );
450                                         $client->respond( $_METHODS[$api_level]{$api_name} );
451                                         $log->debug( "responed with definition for method [$api_name]", INTERNAL );
452                                 }
453                         }
454                 }
455         }
456
457         return undef;
458 }
459 __PACKAGE__->register_method(
460         stream => 1,
461         method => 'introspect',
462         api_name => 'opensrf.system.method.all'
463 );
464
465 __PACKAGE__->register_method(
466         stream => 1,
467         method => 'introspect',
468         argc => 1,
469         api_name => 'opensrf.system.method'
470 );
471
472 sub make_stream_atomic {
473         my $self = shift;
474         my $req = shift;
475         my @args = @_;
476
477         (my $m_name = $self->api_name) =~ s/\.atomic$//o;
478         my @results = $self->method_lookup($m_name)->run(@args);
479
480         if (@results == 1) {
481                 return $results[0];
482         }
483         return \@results;
484 }
485
486
487 1;