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