]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/perlmods/OpenSRF/Application.pm
added the rest of the magic remote subrequest stuff
[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 );
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( ref( $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 = AppSession->create('settings');
230         try {
231                 $session->connect;
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->content;
242
243         $req->finish;
244         $session->finish;
245         $session->disconnect;
246
247         my %u_list = map { ($_ => 1) } @$list;
248
249         for my $class ( keys %u_list ) {
250                 populate_remote_method_cache($class);
251         }
252 }
253
254 sub populate_remote_method_cache {
255         my $class = shift;
256
257         my $session = AppSession->create($class);
258         try {
259                 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
260
261                 my $req = $session->request( 'opensrf.system.method.all' );
262
263                 while (my $method = $req->recv) {
264                         next if (UNIVERSAL::isa($method, 'Error'));
265
266                         $method = $method->content;
267                         next if ( exists($_METHODS[$$method{api_level}]) &&
268                                 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
269                         $method->{remote} = 1;
270                         $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
271                 }
272
273                 $req->finish;
274                 $session->finish;
275                 $session->disconnect;
276
277         } catch Error with {
278                 my $e = shift;
279                 $log->debug( "Remote subrequest returned an error:\n". $e );
280                 return undef;
281         };
282 }
283
284 sub method_lookup {             
285         my $self = shift;
286         my $method = shift;
287         my $proto = shift;
288         my $no_recurse = shift || 0;
289
290         # this instead of " || 1;" above to allow api_level 0
291         $proto = 1 unless (defined $proto);
292
293         my $class = ref($self) || $self;
294
295         $log->debug("Lookup of [$method] by [$class]", DEBUG);
296         $log->debug("Available methods\n".Dumper(\@_METHODS), INTERNAL);
297
298         my $meth;
299         if (__PACKAGE__->thunk) {
300                 for my $p ( reverse(1 .. $proto) ) {
301                         if (exists $_METHODS[$p]{$method}) {
302                                 $meth = $_METHODS[$p]{$method};
303                         }
304                 }
305         } else {
306                 if (exists $_METHODS[$proto]{$method}) {
307                         $meth = $_METHODS[$proto]{$method};
308                 }
309         }
310
311         if (defined $meth) {
312                 $log->debug("Looks like we found [$method]!", DEBUG);
313                 $log->debug("Method object is ".Dumper($meth), INTERNAL);
314         } elsif (!$no_recurse) {
315                 retrieve_remote_apis();
316                 $meth = $self->method_lookup($method,$proto,1);
317         }
318
319         return $meth;
320 }
321
322 sub run {
323         my $self = shift;
324         my $req = shift;
325
326         my $resp;
327
328         if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
329                 $log->debug("Creating a SubRequest object", DEBUG);
330                 unshift @_, $req;
331                 $req = OpenSRF::AppSubrequest->new;
332         } else {
333                 $log->debug("This is a top level request", DEBUG);
334         }
335
336         if (!$self->{remote}) {
337                 my $code ||= \&{$self->{package} . '::' . $self->{method}};
338                 $resp = $code->($self, $req, @_);
339
340                 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
341                         $req->respond($resp) if (defined $resp);
342                         return $req->responses;
343                 } else {
344                         $log->debug("A top level Request object is responding $resp", DEBUG);
345                         return $resp;
346                 }
347         } else {
348                 my $session = AppSession->create($self->{server_class});
349                 try {
350                         $session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
351                         my $remote_req = $session->request( $self->{api_name}, @_ );
352                         while (my $remote_resp = $remote_req->recv->content) {
353                                 $req->respond( $remote_resp );
354                         }
355                         return $req->responses;
356
357                 } catch Error with {
358                         my $e = shift;
359                         $log->debug( "Remote subrequest returned an error:\n". $e );
360                         return undef;
361                 };
362         }
363         # huh? how'd we get here...
364         return undef;
365 }
366
367 sub introspect {
368         my $self = shift;
369         my $client = shift;
370         my $method = shift;
371
372         $method = undef if ($self->{api_name} =~ /all$/o);
373
374         for my $api_level ( 1 .. $#_METHODS ) {
375                 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
376                         if (!$_METHODS[$api_level]{$api_name}{remote}) {
377                                 if (defined($method)) {
378                                         if ($api_name =~ /$method/) {
379                                                 $client->respond( $_METHODS[$api_level]{$api_name} );
380                                         }
381                                 } else {
382                                         $client->respond( $_METHODS[$api_level]{$api_name} );
383                                 }
384                         }
385                 }
386         }
387
388         return undef;
389 }
390 __PACKAGE__->register_method(
391         stream => 1,
392         method => 'introspect',
393         api_name => 'opensrf.system.method.all'
394 );
395
396 __PACKAGE__->register_method(
397         stream => 1,
398         method => 'introspect',
399         argc => 1,
400         api_name => 'opensrf.system.method'
401 );
402
403 sub make_stream_atomic {
404         my $self = shift;
405         my $req = shift;
406         my @args = @_;
407
408         (my $m_name = $self->api_name) =~ s/\.atomic$//o;
409         my @results = $self->method_lookup($m_name)->run(@args);
410
411         if (@results == 1) {
412                 return $results[0];
413         }
414         return \@results;
415 }
416
417
418 1;