]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/perlmods/OpenSRF/Application.pm
9c9c30a52b8d527ed9425cd8e4903a4eb28a491b
[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         $args{code} ||= \&{$app . '::' . $args{method}};
219
220         $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
221
222         __PACKAGE__->register_method(
223                 stream => 0,
224                 api_name => $args{api_name}.'.atomic',
225                 method => 'make_stream_atomic'
226         ) if ($args{stream});
227 }
228
229 sub retrieve_remote_apis {
230         my $session = AppSession->create('settings');
231         try {
232                 $session->connect;
233         } catch Error with {
234                 my $e = shift;
235                 $log->debug( "Remote subrequest returned an error:\n". $e );
236                 return undef;
237         } finally {
238                 return undef unless ($session->state == $session->CONNECTED);
239         };
240
241         my $req = $session->request( 'opensrf.settings.xpath.get' );
242         my $list = $req->recv->content;
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;
260         } catch Error with {
261                 my $e = shift;
262                 $log->debug( "Remote subrequest returned an error:\n". $e );
263                 return undef;
264         } finally {
265                 return undef unless ($session->state == $session->CONNECTED);
266         };
267
268         my $req = $session->request( 'opensrf.settings.xpath.get' );
269
270         while (my $method = $req->recv->content) {
271                 $method->{remote} = 1;
272                 $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
273         }
274
275         $req->finish;
276         $session->finish;
277         $session->disconnect;
278 }
279
280 sub method_lookup {             
281         my $self = shift;
282         my $method = shift;
283         my $proto = shift;
284         my $no_recurse = shift || 0;
285
286         # this instead of " || 1;" above to allow api_level 0
287         $proto = 1 unless (defined $proto);
288
289         my $class = ref($self) || $self;
290
291         $log->debug("Lookup of [$method] by [$class]", DEBUG);
292         $log->debug("Available methods\n".Dumper(\@_METHODS), INTERNAL);
293
294         my $meth;
295         if (__PACKAGE__->thunk) {
296                 for my $p ( reverse(1 .. $proto) ) {
297                         if (exists $_METHODS[$p]{$method}) {
298                                 $meth = $_METHODS[$p]{$method};
299                         }
300                 }
301         } else {
302                 if (exists $_METHODS[$proto]{$method}) {
303                         $meth = $_METHODS[$proto]{$method};
304                 }
305         }
306
307         if (defined $meth) {
308                 $log->debug("Looks like we found [$method]!", DEBUG);
309                 $log->debug("Method object is ".Dumper($meth), INTERNAL);
310         } elsif (!$no_recurse) {
311
312                 # XXX Remvoe this to activate the magic!
313                 return $meth;
314                 # XXX Remvoe this to activate the magic!
315                 
316                 retrieve_remote_apis();
317                 $self->method_lookup($method,$proto,1);
318         }
319
320         return $meth;
321 }
322
323 sub run {
324         my $self = shift;
325         my $req = shift;
326
327         my $resp;
328
329         if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
330                 $log->debug("Creating a SubRequest object", DEBUG);
331                 unshift @_, $req;
332                 $req = OpenSRF::AppSubrequest->new;
333         } else {
334                 $log->debug("This is a top level request", DEBUG);
335         }
336
337         if (!$self->{remote}) {
338                 my $code ||= \&{$server_class . '::' . $self->{method}};
339                 $resp = $code->($self, $req, @_);
340
341                 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
342                         $req->respond($resp) if (defined $resp);
343                         return $req->responses;
344                 } else {
345                         $log->debug("A top level Request object is responding $resp", DEBUG);
346                         return $resp;
347                 }
348         } else {
349                 my $session = AppSession->create($self->{server_class});
350                 try {
351                         $session->connect;
352                 } catch Error with {
353                         my $e = shift;
354                         $log->debug( "Remote subrequest returned an error:\n". $e );
355                         return undef;
356                 } finally {
357                         return undef unless ($session->state == $session->CONNECTED);
358                 };
359
360                 my $remote_req = $session->request( $self->{api_name}, @_ );
361                 while (my $remote_resp = $remote_req->recv) {
362                         $req->respond( $remote_resp );
363                 }
364                 return $req->responses;
365         }
366         # huh? how'd we get here...
367         return undef;
368 }
369
370 sub introspect {
371         my $self = shift;
372         my $client = shift;
373
374         for my $api_level ( 1 .. $#_METHODS ) {
375                 $client->respond( { $api_level => $_METHODS[$api_level] } );
376         }
377
378         return undef;
379 }
380 __PACKAGE__->register_method(
381         stream => 1,
382         method => 'introspect',
383         api_name => 'opensrf.system.method_list'
384 );
385
386 sub make_stream_atomic {
387         my $self = shift;
388         my $req = shift;
389         my @args = @_;
390
391         (my $m_name = $self->api_name) =~ s/\.atomic$//o;
392         my @results = $self->method_lookup($m_name)->run(@args);
393
394         if (@results == 1) {
395                 return $results[0];
396         }
397         return \@results;
398 }
399
400
401 1;