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