]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/perlmods/OpenSRF/Application.pm
27236903492b07a75919f43bad9ad7c1a64fd813
[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 1 unless ref($self);
28         return $self->{package};
29 }
30
31 sub signature {
32         my $self = shift;
33         return 0 unless ref($self);
34         return $self->{signature};
35 }
36
37 sub argc {
38         my $self = shift;
39         return 0 unless ref($self);
40         return $self->{argc};
41 }
42
43 sub api_name {
44         my $self = shift;
45         return 1 unless ref($self);
46         return $self->{api_name};
47 }
48
49 sub api_level {
50         my $self = shift;
51         return 1 unless ref($self);
52         return $self->{api_level};
53 }
54
55 sub server_class {
56         my $class = shift;
57         if($class) {
58                 $server_class = $class;
59         }
60         return $server_class;
61 }
62
63 sub thunk {
64         my $self = shift;
65         my $flag = shift;
66         $thunk = $flag if (defined $flag);
67         return $thunk;
68 }
69
70 sub application_implementation {
71         my $self = shift;
72         my $app = shift;
73
74         if (defined $app) {
75                 $_app = $app;
76                 $_app->use;
77                 if( $@ ) {
78                         $log->error( "Error loading application_implementation: $app -> $@", ERROR);
79                 }
80
81         }
82
83         return $_app;
84 }
85
86 sub handler {
87         my ($self, $session, $app_msg) = @_;
88
89         if( ! $app_msg ) {
90                 return 1;  # error?
91         }
92
93         my $app = $self->application_implementation;
94
95         if ($session->last_message_type eq 'REQUEST') {
96
97                 my $method_name = $app_msg->method;
98                 my $method_proto = $session->last_message_api_level;
99
100                 my $coderef = $app->method_lookup( $method_name, $method_proto, 1, 1 );
101
102                 unless ($coderef) {
103                         $session->status( OpenSRF::DomainObject::oilsMethodException->new( 
104                                                 statusCode => STATUS_NOTFOUND(),
105                                                 status => "Method [$method_name] not found for $app"));
106                         return 1;
107                 }
108
109                 unless ($session->continue_request) {
110                         $session->status(
111                                 OpenSRF::DomainObject::oilsConnectStatus->new(
112                                                 statusCode => STATUS_REDIRECTED(),
113                                                 status => 'Disconnect on max requests' ) );
114                         $session->kill_me;
115                         return 1;
116                 }
117
118                 if (ref $coderef) {
119                         my @args = $app_msg->params;
120                         my $appreq = OpenSRF::AppRequest->new( $session );
121
122                         $log->debug( "in_request = $in_request : [" . $appreq->threadTrace."]", INTERNAL );
123                         if( $in_request ) {
124                                 $log->debug( "Pushing onto pending requests: " . $appreq->threadTrace, DEBUG );
125                                 push @pending_requests, [ $appreq, \@args, $coderef ]; 
126                                 return 1;
127                         }
128
129
130                         $in_request++;
131
132                         $log->debug( "Executing coderef for {$method_name}", INTERNAL );
133
134                         my $resp;
135                         try {
136                                 # un-if(0) this block to enable param checking based on signature and argc
137                                 if (0) {
138                                         if (@args < $coderef->argc) {
139                                                 die     "Not enough params passed to ".
140                                                         $coderef->api_name." : requires ". $coderef->argc
141                                         }
142                                         if (@args) {
143                                                 my $sig = $coderef->signature;
144                                                 if ($sig && exists $sig->{params}) {
145                                                         for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
146                                                                 my $s = $sig->{params}->[$p];
147                                                                 my $a = $args[$p];
148                                                                 if ($s->{class} && JSON->lookup_hint(ref $a) ne $s->{class}) {
149                                                                         die "Incorrect param class at position $p : should be a '$$s{class}'";
150                                                                 } elsif ($s->{type}) {
151                                                                         if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
152                                                                                 die "Incorrect param type at position $p : should be an 'object'";
153                                                                         } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
154                                                                                 die "Incorrect param type at position $p : should be an 'array'";
155                                                                         } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
156                                                                                 die "Incorrect param type at position $p : should be a 'number'";
157                                                                         } elsif (lc($s->{type}) eq 'string' && ref($a)) {
158                                                                                 die "Incorrect param type at position $p : should be a 'string'";
159                                                                         }
160                                                                 }
161                                                         }
162                                                 }
163                                         }
164                                 }
165
166                                 my $start = time();
167                                 warn "About to run...\n";
168                                 $resp = $coderef->run( $appreq, @args); 
169                                 warn "Done running...\n";
170                                 my $time = sprintf '%.3f', time() - $start;
171
172                                 $log->debug( "Method duration for [$method_name]:  ". $time );
173                                 if( defined( $resp ) ) {
174                                         $appreq->respond_complete( $resp );
175                                 } else {
176                                         $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
177                                                                 statusCode => STATUS_COMPLETE(),
178                                                                 status => 'Request Complete' ) );
179                                 }
180                         } catch Error with {
181                                 my $e = shift;
182                                 warn "Caught error from 'run' method: $e\n";
183
184                                 if(UNIVERSAL::isa($e,"Error")) {
185                                         $e = $e->stringify();
186                                 } 
187                                 my $sess_id = $session->session_id;
188                                 $session->status(
189                                         OpenSRF::DomainObject::oilsMethodException->new(
190                                                         statusCode      => STATUS_INTERNALSERVERERROR(),
191                                                         status          => " *** Call to [$method_name] failed for session ".
192                                                                            "[$sess_id], thread trace ".
193                                                                            "[".$appreq->threadTrace."]:\n$e\n"
194                                         )
195                                 );
196                         };
197
198
199
200                         # ----------------------------------------------
201
202
203                         # XXX may need this later
204                         # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
205
206                         $in_request--;
207
208                         $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
209
210                         # cycle through queued requests
211                         while( my $aref = shift @pending_requests ) {
212                                 $in_request++;
213                                 my $resp;
214                                 try {
215                                         # un-if(0) this block to enable param checking based on signature and argc
216                                         if (0) {
217                                                 if (@args < $aref->[2]->argc) {
218                                                         die     "Not enough params passed to ".
219                                                                 $aref->[2]->api_name." : requires ". $aref->[2]->argc
220                                                 }
221                                                 if (@args) {
222                                                         my $sig = $aref->[2]->signature;
223                                                         if ($sig && exists $sig->{params}) {
224                                                                 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
225                                                                         my $s = $sig->{params}->[$p];
226                                                                         my $a = $args[$p];
227                                                                         if ($s->{class} && JSON->lookup_hint(ref $a) ne $s->{class}) {
228                                                                                 die "Incorrect param class at position $p : should be a '$$s{class}'";
229                                                                         } elsif ($s->{type}) {
230                                                                                 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
231                                                                                         die "Incorrect param type at position $p : should be an 'object'";
232                                                                                 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
233                                                                                         die "Incorrect param type at position $p : should be an 'array'";
234                                                                                 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
235                                                                                         die "Incorrect param type at position $p : should be a 'number'";
236                                                                                 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
237                                                                                         die "Incorrect param type at position $p : should be a 'string'";
238                                                                                 }
239                                                                         }
240                                                                 }
241                                                         }
242                                                 }
243                                         }
244
245                                         my $start = time;
246                                         my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
247                                         my $time = sprintf '%.3f', time - $start;
248                                         $log->debug( "Method duration for [".$aref->[2]->api_name." -> ".join(', ',@{$aref->[1]}).']:  '.$time, DEBUG );
249
250                                         $appreq = $aref->[0];   
251                                         if( ref( $response ) ) {
252                                                 $appreq->respond_complete( $response );
253                                         } else {
254                                                 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
255                                                                         statusCode => STATUS_COMPLETE(),
256                                                                         status => 'Request Complete' ) );
257                                         }
258                                         $log->debug( "Executed: " . $appreq->threadTrace, INTERNAL );
259                                 } catch Error with {
260                                         my $e = shift;
261                                         if(UNIVERSAL::isa($e,"Error")) {
262                                                 $e = $e->stringify();
263                                         }
264                                         $session->status(
265                                                 OpenSRF::DomainObject::oilsMethodException->new(
266                                                                 statusCode => STATUS_INTERNALSERVERERROR(),
267                                                                 status => "Call to [".$aref->[2]->api_name."] faild:  $e"
268                                                 )
269                                         );
270                                 };
271                                 $in_request--;
272                         }
273
274                         return 1;
275                 } 
276
277                 $log->info("Received non-REQUEST message in Application handler");
278
279                 my $res = OpenSRF::DomainObject::oilsMethodException->new( 
280                                 status => "Received non-REQUEST message in Application handler");
281                 $session->send('ERROR', $res);
282                 $session->kill_me;
283                 return 1;
284
285         } else {
286                 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
287         }
288
289         $session->last_message_type('');
290         $session->last_message_api_level('');
291
292         return 1;
293 }
294
295 sub is_registered {
296         my $self = shift;
297         my $api_name = shift;
298         my $api_level = shift || 1;
299         return exists($_METHODS[$api_level]{$api_name});
300 }
301
302
303 sub normalize_whitespace {
304         my $txt = shift;
305
306         $txt =~ s/^\s+//gso;
307         $txt =~ s/\s+$//gso;
308         $txt =~ s/\s+/ /gso;
309         $txt =~ s/\n//gso;
310         $txt =~ s/\. /\.  /gso;
311
312         return $txt;
313 }
314
315 sub parse_string_signature {
316         my $string = shift;
317         return [] unless $string;
318         my @chunks = split(/\@/so, $string);
319
320         my @params;
321         my $ret;
322         my $desc = '';
323         for (@chunks) {
324                 if (/^return (.+)$/so) {
325                         $ret = [normalize_whitespace($1)];
326                 } elsif (/^param (\w+) \b(.+)$/so) {
327                         push @params, [ $1, normalize_whitespace($2) ];
328                 } else {
329                         $desc .= '@' if $desc;
330                         $desc .= $_;
331                 }
332         }
333
334         return [normalize_whitespace($desc),\@params, $ret];
335 }
336
337 sub parse_array_signature {
338         my $array = shift;
339         my ($d,$p,$r) = @$array;
340         return {} unless ($d or $p or $r);
341
342         return {
343                 desc    => $d,
344                 params  => [
345                         map { 
346                                 { name  => $$_[0],
347                                   desc  => $$_[1],
348                                   type  => $$_[2],
349                                   class => $$_[3],
350                                 }
351                         } @$p
352                 ],
353                 'return'=>
354                         { desc  => $$r[0],
355                           type  => $$r[1],
356                           class => $$r[2],
357                         }
358         };
359 }
360
361 sub register_method {
362         my $self = shift;
363         my $app = ref($self) || $self;
364         my %args = @_;
365
366
367         throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
368
369         $args{api_level} = 1 unless(defined($args{api_level}));
370         $args{stream} ||= 0;
371         $args{remote} ||= 0;
372         $args{argc} ||= 0;
373         $args{package} ||= $app;                
374         $args{server_class} = server_class();
375         $args{api_name} ||= $args{server_class} . '.' . $args{method};
376
377         # un-if(0) this block to enable signature parsing
378         if (!$args{signature}) {
379                 if ($args{notes} && !ref($args{notes})) {
380                         $args{signature} =
381                                 parse_array_signature( parse_string_signature( $args{notes} ) );
382                 }
383         } elsif( !ref($args{signature}) ) {
384                 $args{signature} =
385                         parse_array_signature( parse_string_signature( $args{signature} ) );
386         } elsif( ref($args{signature}) eq 'ARRAY') {
387                 $args{signature} =
388                         parse_array_signature( $args{signature} );
389         }
390         
391         unless ($args{object_hint}) {
392                 ($args{object_hint} = $args{package}) =~ s/::/_/go;
393         }
394
395         JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
396
397         $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
398
399         __PACKAGE__->register_method(
400                 stream => 0,
401                 argc => $args{argc},
402                 api_name => $args{api_name}.'.atomic',
403                 method => 'make_stream_atomic',
404                 notes => "This is a system generated method.  Please see the definition for $args{api_name}",
405         ) if ($args{stream});
406 }
407
408 sub retrieve_remote_apis {
409         my $method = shift;
410         my $session = OpenSRF::AppSession->create('router');
411         try {
412                 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
413         } catch Error with {
414                 my $e = shift;
415                 $log->debug( "Remote subrequest returned an error:\n". $e );
416                 return undef;
417         } finally {
418                 return undef unless ($session->state == $session->CONNECTED);
419         };
420
421         my $req = $session->request( 'opensrf.router.info.class.list' );
422         my $list = $req->recv;
423
424         if( UNIVERSAL::isa($list,"Error") ) {
425                 throw $list;
426         }
427
428         my $content = $list->content;
429
430         $req->finish;
431         $session->finish;
432         $session->disconnect;
433
434         my %u_list = map { ($_ => 1) } @$content;
435
436         for my $class ( keys %u_list ) {
437                 next if($class eq $server_class);
438                 populate_remote_method_cache($class, $method);
439         }
440 }
441
442 sub populate_remote_method_cache {
443         my $class = shift;
444         my $meth = shift;
445
446         my $session = OpenSRF::AppSession->create($class);
447         try {
448                 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
449
450                 my $call = 'opensrf.system.method.all' unless (defined $meth);
451                 $call = 'opensrf.system.method' if (defined $meth);
452
453                 my $req = $session->request( $call, $meth );
454
455                 while (my $method = $req->recv) {
456                         next if (UNIVERSAL::isa($method, 'Error'));
457
458                         $method = $method->content;
459                         next if ( exists($_METHODS[$$method{api_level}]) &&
460                                 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
461                         $method->{remote} = 1;
462                         bless($method, __PACKAGE__ );
463                         $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
464                 }
465
466                 $req->finish;
467                 $session->finish;
468                 $session->disconnect;
469
470         } catch Error with {
471                 my $e = shift;
472                 $log->debug( "Remote subrequest returned an error:\n". $e );
473                 return undef;
474         };
475 }
476
477 sub method_lookup {             
478         my $self = shift;
479         my $method = shift;
480         my $proto = shift;
481         my $no_recurse = shift || 0;
482         my $no_remote = shift || 0;
483
484         # this instead of " || 1;" above to allow api_level 0
485         $proto = $self->api_level unless (defined $proto);
486
487         my $class = ref($self) || $self;
488
489         $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
490         $log->debug("Available methods\n\t".join("\n\t", keys %{ $_METHODS[$proto] }), INTERNAL);
491
492         my $meth;
493         if (__PACKAGE__->thunk) {
494                 for my $p ( reverse(1 .. $proto) ) {
495                         if (exists $_METHODS[$p]{$method}) {
496                                 $meth = $_METHODS[$p]{$method};
497                         }
498                 }
499         } else {
500                 if (exists $_METHODS[$proto]{$method}) {
501                         $meth = $_METHODS[$proto]{$method};
502                 }
503         }
504
505         if (defined $meth) {
506                 if($no_remote and $meth->{remote}) {
507                         $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
508                         return undef;
509                 }
510
511         } elsif (!$no_recurse) {
512                 $log->debug("We didn't find [$method], asking everyone else.", DEBUG);
513                 retrieve_remote_apis($method);
514                 $meth = $self->method_lookup($method,$proto,1);
515         }
516
517         return $meth;
518 }
519
520 sub run {
521         my $self = shift;
522         my $req = shift;
523
524         my $resp;
525         my @params = @_;
526
527         if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
528                 $log->debug("Creating a SubRequest object", DEBUG);
529                 unshift @params, $req;
530                 $req = OpenSRF::AppSubrequest->new;
531         } else {
532                 $log->debug("This is a top level request", DEBUG);
533         }
534
535         if (!$self->{remote}) {
536                 my $code = \&{$self->{package} . '::' . $self->{method}};
537                 my $err = undef;
538
539                 try {
540                         $resp = $code->($self, $req, @params);
541
542                 } catch Error with {
543                         $err = shift;
544
545                         if( ref($self) eq 'HASH') {
546                                 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$err\n", ERROR);
547                         }
548                 };
549
550                 if($err) {
551                         if(UNIVERSAL::isa($err,"Error")) { 
552                                 throw $err;
553                         } else {
554                                 die $err->stringify; 
555                         }
556                 }
557
558
559                 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
560
561                 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
562                         $req->respond($resp) if (defined $resp);
563                         $log->debug("SubRequest object is responding with : " . join(" ",$req->responses), DEBUG);
564                         return $req->responses;
565                 } else {
566                         $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
567                         return $resp;
568                 }
569         } else {
570                 my $session = OpenSRF::AppSession->create($self->{server_class});
571                 try {
572                         #$session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
573                         my $remote_req = $session->request( $self->{api_name}, @params );
574                         while (my $remote_resp = $remote_req->recv) {
575                                 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
576                                 if( UNIVERSAL::isa($remote_resp,"Error") ) {
577                                         throw $remote_resp;
578                                 }
579                                 $req->respond( $remote_resp->content );
580                         }
581                         $remote_req->finish();
582
583                 } catch Error with {
584                         my $e = shift;
585                         $log->debug( "Remote subrequest returned an error:\n". $e );
586                         return undef;
587                 };
588
589                 if ($session) {
590                         $session->disconnect();
591                         $session->finish();
592                 }
593
594                 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
595
596                 return $req->responses;
597         }
598         # huh? how'd we get here...
599         return undef;
600 }
601
602 sub introspect {
603         my $self = shift;
604         my $client = shift;
605         my $method = shift;
606         my $limit = shift;
607         my $offset = shift;
608
609         if ($self->api_name =~ /all$/o) {
610                 $offset = $limit;
611                 $limit = $method;
612                 $method = undef; 
613         }
614
615         my ($seen,$returned) = (0,0);
616         for my $api_level ( reverse(1 .. $#_METHODS) ) {
617                 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
618                         if (!$offset || $offset <= $seen) {
619                                 if (!$_METHODS[$api_level]{$api_name}{remote}) {
620                                         if (defined($method)) {
621                                                 if ($api_name =~ $method) {
622                                                         if (!$limit || $returned < $limit) {
623                                                                 $client->respond( $_METHODS[$api_level]{$api_name} );
624                                                                 $returned++;
625                                                         }
626                                                 }
627                                         } else {
628                                                 if (!$limit || $returned < $limit) {
629                                                         $client->respond( $_METHODS[$api_level]{$api_name} );
630                                                         $returned++;
631                                                 }
632                                         }
633                                 }
634                         }
635                         $seen++;
636                 }
637         }
638
639         return undef;
640 }
641 __PACKAGE__->register_method(
642         stream => 1,
643         method => 'introspect',
644         api_name => 'opensrf.system.method.all',
645         argc => 0,
646         signature => {
647                 desc => q/This method is used to introspect an entire OpenSRF Application/,
648                 return => {
649                         desc => q/A stream of objects describing the methods available via this OpenSRF Application/,
650                         type => 'object'
651                 }
652         },
653 );
654 __PACKAGE__->register_method(
655         stream => 1,
656         method => 'introspect',
657         argc => 1,
658         api_name => 'opensrf.system.method',
659         argc => 1,
660         signature => {
661                 desc => q/Use this method to get the definition of a single OpenSRF Method/,
662                 params => [
663                         { desc => q/The method to introspect/,
664                           type => 'string' },
665                 ],
666                 return => { desc => q/An object describing the method requested, or an error if it can't be found/,
667                             type => 'object' }
668         },
669 );
670
671 sub echo_method {
672         my $self = shift;
673         my $client = shift;
674         my @args = @_;
675
676         $client->respond( $_ ) for (@args);
677         return undef;
678 }
679 __PACKAGE__->register_method(
680         stream => 1,
681         method => 'echo_method',
682         argc => 1,
683         api_name => 'opensrf.system.echo',
684         signature => {
685                 desc => q/A test method that will echo back it's arguments in a streaming response/,
686                 params => [
687                         { desc => q/One or more arguments to echo back/ }
688                 ],
689                 return => { desc => q/A stream of the arguments passed/ }
690         },
691 );
692
693 sub time_method {
694         my( $self, $conn ) = @_;
695         return CORE::time;
696 }
697 __PACKAGE__->register_method(
698         method => 'time_method',
699         argc => 0,
700         api_name => 'opensrf.system.time',
701         signature => {
702                 desc => q/Returns the current system time as epoch seconds/,
703                 return => { desc => q/epoch seconds/ }
704         }
705 );
706
707 sub make_stream_atomic {
708         my $self = shift;
709         my $req = shift;
710         my @args = @_;
711
712         (my $m_name = $self->api_name) =~ s/\.atomic$//o;
713         my @results = $self->method_lookup($m_name)->run(@args);
714
715         return \@results;
716 }
717
718
719 1;
720
721