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