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