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