]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/perlmods/OpenSRF/Application.pm
cef8e6eea048a9c809f2d4684fdea14c5fb1e084
[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 OpenSRF::UnixServer;  # to get the server class from UnixServer::App
13
14 sub DESTROY{};
15
16 use strict;
17 use warnings;
18
19 $log = 'OpenSRF::Utils::Logger';
20
21 our $in_request = 0;
22 our @pending_requests;
23
24 sub api_name {
25         my $self = shift;
26         return $self->{api_name};
27 }
28
29 sub server_class {
30         my $class = shift;
31         if($class) {
32                 $server_class = $class;
33         }
34         return $server_class;
35 }
36
37 sub thunk {
38         my $self = shift;
39         my $flag = shift;
40         $thunk = $flag if (defined $flag);
41         return $thunk;
42 }
43
44 sub application_implementation {
45         my $self = shift;
46         my $app = shift;
47
48         if (defined $app) {
49                 $_app = $app;
50                 eval "use $_app;";
51                 if( $@ ) {
52                         $log->error( "Error loading application_implementation: $app -> $@", ERROR);
53                 }
54
55         }
56
57         return $_app;
58 }
59
60 sub handler {
61         my ($self, $session, $app_msg) = @_;
62
63         if( ! $app_msg ) {
64                 return 0;  # error?
65         }
66
67         $log->debug( "In Application::handler()", DEBUG );
68
69         my $app = $self->application_implementation;
70
71         if( $app ) {
72                 $log->debug( "Application is $app", DEBUG);
73         }
74         $log->debug( "Message is ".$app_msg->toString(1), INTERNAL);
75
76
77         if ($session->last_message_type eq 'REQUEST') {
78                 $log->debug( "We got a REQUEST: ". $app_msg->method, INFO );
79
80                 my $method_name = $app_msg->method;
81                 $log->debug( " * Looking up $method_name inside $app", DEBUG);
82
83                 my $method_proto = $session->last_message_api_level;
84                 $log->debug( " * Method API Level [$method_proto]", DEBUG);
85
86                 my $coderef = $app->method_lookup( $method_name, $method_proto, 1, 1 );
87
88                 unless ($coderef) {
89                         $session->status( OpenSRF::DomainObject::oilsMethodException->new() );
90                         return 1;
91                 }
92
93                 $log->debug( " (we got coderef $coderef", DEBUG);
94
95                 unless ($session->continue_request) {
96                         $session->status(
97                                 OpenSRF::DomainObject::oilsConnectStatus->new(
98                                                 statusCode => STATUS_REDIRECTED(),
99                                                 status => 'Disconnect on max requests' ) );
100                         $session->kill_me;
101                         return 1;
102                 }
103
104                 if (ref $coderef) {
105                         my @args = $app_msg->params;
106                         my $appreq = OpenSRF::AppRequest->new( $session );
107
108                         $log->debug( "in_request = $in_request : [" . $appreq->threadTrace."]", DEBUG );
109                         if( $in_request ) {
110                                 $log->debug( "Pushing onto pending requests: " . $appreq->threadTrace, DEBUG );
111                                 push @pending_requests, [ $appreq, \@args, $coderef ]; 
112                                 return 1;
113                         }
114
115
116                         $in_request++;
117
118                         $log->debug( "Executing coderef for {$method_name -> ".join(', ', @args)."}", INTERNAL );
119
120                         my $resp;
121                         try {
122                                 my $start = time();
123                                 $resp = $coderef->run( $appreq, @args); 
124                                 my $time = sprintf '%.3f', time() - $start;
125                                 $log->debug( "Method duration for {$method_name -> ".join(', ', @args)."}:  ". $time, DEBUG );
126                                 if( defined( $resp ) ) {
127                                         #$log->debug( "Calling respond_complete: ". $resp->toString(), INTERNAL );
128                                         $appreq->respond_complete( $resp );
129                                 } else {
130                                         $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
131                                                                 statusCode => STATUS_COMPLETE(),
132                                                                 status => 'Request Complete' ) );
133                                 }
134                         } catch Error with {
135                                 my $e = shift;
136                                 $e = $e->{-text} || $e->message if (ref $e);
137                                 my $sess_id = $session->session_id;
138                                 $session->status(
139                                         OpenSRF::DomainObject::oilsMethodException->new(
140                                                         statusCode      => STATUS_INTERNALSERVERERROR(),
141                                                         status          => " *** Call to [$method_name] failed for session ".
142                                                                            "[$sess_id], thread trace [".$appreq->threadTrace."]:\n".$e
143                                         )
144                                 );
145                         };
146
147
148
149                         # ----------------------------------------------
150
151
152                         # XXX may need this later
153                         # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
154
155                         $in_request--;
156
157                         $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
158
159                         # cycle through queued requests
160                         while( my $aref = shift @pending_requests ) {
161                                 $in_request++;
162                                 my $resp;
163                                 try {
164                                         my $start = time;
165                                         my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
166                                         my $time = sprintf '%.3f', time - $start;
167                                         $log->debug( "Method duration for {[".$aref->[2]->name." -> ".join(', ',@{$aref->[1]}).'}:  '.$time, DEBUG );
168
169                                         $appreq = $aref->[0];   
170                                         if( ref( $response ) ) {
171                                                 $log->debug( "Calling respond_complete: ". $response->toString(), INTERNAL );
172                                                 $appreq->respond_complete( $response );
173                                         } else {
174                                                 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
175                                                                         statusCode => STATUS_COMPLETE(),
176                                                                         status => 'Request Complete' ) );
177                                         }
178                                         $log->debug( "Executed: " . $appreq->threadTrace, DEBUG );
179                                 } catch Error with {
180                                         my $e = shift;
181                                         $session->status(
182                                                 OpenSRF::DomainObject::oilsMethodException->new(
183                                                                 statusCode => STATUS_INTERNALSERVERERROR(),
184                                                                 status => "Call to [".$aref->[2]->name."] faild:  ".$e->{-text}
185                                                 )
186                                         );
187                                 };
188                                 $in_request--;
189                         }
190
191                         return 1;
192                 } 
193                 my $res = OpenSRF::DomainObject::oilsMethodException->new;
194                 $session->send('ERROR', $res);
195                 $session->kill_me;
196                 return 1;
197
198         } else {
199                 $log->debug( "Pushing ". $app_msg->toString ." onto queue", INTERNAL );
200                 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
201         }
202
203         $session->last_message_type('');
204         $session->last_message_api_level('');
205
206         return 1;
207 }
208
209 sub register_method {
210         my $self = shift;
211         my $app = ref($self) || $self;
212         my %args = @_;
213
214
215         throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
216
217         $args{api_level} ||= 1;
218         $args{stream} ||= 0;
219         $args{remote} ||= 0;
220         $args{package} = $app;                
221         $args{object_hint} ||= '';                
222         $args{server_class} = server_class();
223         $args{api_name} ||= $args{server_class} . '.' . $args{method};
224
225         JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
226
227         $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
228
229         __PACKAGE__->register_method(
230                 stream => 0,
231                 api_name => $args{api_name}.'.atomic',
232                 method => 'make_stream_atomic'
233         ) if ($args{stream});
234 }
235
236 sub retrieve_remote_apis {
237         my $session = OpenSRF::AppSession->create('router');
238         try {
239                 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
240         } catch Error with {
241                 my $e = shift;
242                 $log->debug( "Remote subrequest returned an error:\n". $e );
243                 return undef;
244         } finally {
245                 return undef unless ($session->state == $session->CONNECTED);
246         };
247
248         my $req = $session->request( 'opensrf.router.info.class.list' );
249         my $list = $req->recv;
250
251         if( UNIVERSAL::isa($list,"Error") ) {
252                 throw $list;
253         }
254
255         my $content = $list->content;
256
257         $req->finish;
258         $session->finish;
259         $session->disconnect;
260
261         my %u_list = map { ($_ => 1) } @$content;
262
263         for my $class ( keys %u_list ) {
264                 next if($class eq $server_class);
265                 populate_remote_method_cache($class);
266         }
267 }
268
269 sub populate_remote_method_cache {
270         my $class = shift;
271
272         my $session = OpenSRF::AppSession->create($class);
273         try {
274                 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
275
276                 my $req = $session->request( 'opensrf.system.method.all' );
277
278                 while (my $method = $req->recv) {
279                         next if (UNIVERSAL::isa($method, 'Error'));
280
281                         $method = $method->content;
282                         next if ( exists($_METHODS[$$method{api_level}]) &&
283                                 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
284                         $method->{remote} = 1;
285                         bless($method, __PACKAGE__ );
286                         $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
287                 }
288
289                 $req->finish;
290                 $session->finish;
291                 $session->disconnect;
292
293         } catch Error with {
294                 my $e = shift;
295                 $log->debug( "Remote subrequest returned an error:\n". $e );
296                 return undef;
297         };
298 }
299
300 sub method_lookup {             
301         my $self = shift;
302         my $method = shift;
303         my $proto = shift;
304         my $no_recurse = shift || 0;
305         my $no_remote = shift || 0;
306
307         # this instead of " || 1;" above to allow api_level 0
308         $proto = 1 unless (defined $proto);
309
310         my $class = ref($self) || $self;
311
312         $log->debug("Lookup of [$method] by [$class]", DEBUG);
313         $log->debug("Available methods\n".Dumper(\@_METHODS), INTERNAL);
314
315         my $meth;
316         if (__PACKAGE__->thunk) {
317                 for my $p ( reverse(1 .. $proto) ) {
318                         if (exists $_METHODS[$p]{$method}) {
319                                 $meth = $_METHODS[$p]{$method};
320                         }
321                 }
322         } else {
323                 if (exists $_METHODS[$proto]{$method}) {
324                         $meth = $_METHODS[$proto]{$method};
325                 }
326         }
327
328         if (defined $meth) {
329                 $log->debug("Looks like we found [$method]!", DEBUG);
330                 $log->debug("Method object is ".Dumper($meth), INTERNAL);
331                 if($no_remote and $meth->{remote}) {
332                         $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
333                         return undef;
334                 }
335
336         } elsif (!$no_recurse) {
337                 retrieve_remote_apis();
338                 $meth = $self->method_lookup($method,$proto,1);
339         }
340
341         return $meth;
342 }
343
344 sub run {
345         my $self = shift;
346         my $req = shift;
347
348         my $resp;
349         my @params = @_;
350
351         if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
352                 $log->debug("Creating a SubRequest object", DEBUG);
353                 unshift @params, $req;
354                 $req = OpenSRF::AppSubrequest->new;
355         } else {
356                 $log->debug("This is a top level request", DEBUG);
357         }
358
359         if (!$self->{remote}) {
360                 my $code ||= \&{$self->{package} . '::' . $self->{method}};
361                 $resp = $code->($self, $req, @params);
362
363                 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
364                         $req->respond($resp) if (defined $resp);
365                         $log->debug("A SubRequest object is responding " . join(" ",$req->responses), DEBUG);
366                         return $req->responses;
367                 } else {
368                         $log->debug("A top level Request object is responding $resp", DEBUG);
369                         return $resp;
370                 }
371         } else {
372                 my $session = OpenSRF::AppSession->create($self->{server_class});
373                 try {
374                         $session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
375                         my $remote_req = $session->request( $self->{api_name}, @params );
376                         while (my $remote_resp = $remote_req->recv) {
377                                 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
378                                 if( UNIVERSAL::isa($remote_resp,"Error") ) {
379                                         throw $remote_resp;
380                                 }
381                                 $req->respond( $remote_resp->content );
382                         }
383                         $remote_req->finish();
384                         $session->finish();
385
386                 } catch Error with {
387                         my $e = shift;
388                         $log->debug( "Remote subrequest returned an error:\n". $e );
389                         return undef;
390                 };
391
392                 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
393
394                 return $req->responses;
395         }
396         # huh? how'd we get here...
397         return undef;
398 }
399
400 sub introspect {
401         my $self = shift;
402         my $client = shift;
403         my $method = shift;
404
405         $method = undef if ($self->{api_name} =~ /all$/o);
406
407         for my $api_level ( reverse(1 .. $#_METHODS) ) {
408                 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
409                         if (!$_METHODS[$api_level]{$api_name}{remote}) {
410                                 if (defined($method)) {
411                                         if ($api_name eq $method) {
412                                                 $client->respond( $_METHODS[$api_level]{$api_name} );
413                                         }
414                                 } else {
415                                         $client->respond( $_METHODS[$api_level]{$api_name} );
416                                 }
417                         }
418                 }
419         }
420
421         return undef;
422 }
423 __PACKAGE__->register_method(
424         stream => 1,
425         method => 'introspect',
426         api_name => 'opensrf.system.method.all'
427 );
428
429 __PACKAGE__->register_method(
430         stream => 1,
431         method => 'introspect',
432         argc => 1,
433         api_name => 'opensrf.system.method'
434 );
435
436 sub make_stream_atomic {
437         my $self = shift;
438         my $req = shift;
439         my @args = @_;
440
441         (my $m_name = $self->api_name) =~ s/\.atomic$//o;
442         my @results = $self->method_lookup($m_name)->run(@args);
443
444         if (@results == 1) {
445                 return $results[0];
446         }
447         return \@results;
448 }
449
450
451 1;