blib/lib/MOBY/Async/SimpleServer.pm untested

filter: Statementstmt 0.0% 0 / 242 Branchbran 0.0% 0 / 34 Conditioncond 0.0% 0 / 27 MC/DCmcdc 0.0% 0 / 17 Subroutinesub 0.0% 0 / 13 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 337 CC 5 SCAR 19.0
CC
5
Cov
0%
Destroy
20.0
sync
6.0
error
2.0
CRAP 6.7
1 =pod
2  
3 =head1 NAME
4  
5 MOBY::Async::SimpleServer - a base class for simple Asynchronous MOBY Services
6  
7 =head1 AUTHORS
8  
9 Former developer
10 Enrique de Andres Saiz (enrique.deandres@pcm.uam.es) -
11 INB GNHC-1 (Madrid Science Park, Spain) (2006-2007).
12  
13 Maintainers
14 Jose Maria Fernandez (jmfernandez@cnio.es),
15 Jose Manuel Rodriguez (jmrodriguez@cnio.es) -
16 INB GN2 (CNIO, Spain).
17  
18  
19 =head1 DESCRIPTION
20  
21 Provides a simple class that can be extended to build file based asynchronous
22 services. When submission, these services will just fork the a process,
23 returning inmediately and leaving running the service in background. They store
24 the state information in a file.
25  
26 This class provides the WS-ResourceProperty and WS-ResourceLifetime methods
27 required for Asynchronous MOBY Services:
28  
29 =over
30  
31 =item WS-ResourceProperty:
32  
33 GetResourceProperty
34 GetMultipleResourceProperties
35  
36 =item WS-ResourceLifetime:
37  
38 Destroy
39  
40 =back
41  
42 Additionally, this class provides other methods in order to carry up
43 synchronous or asynchronous request of the service.
44  
45 =head1 METHODS
46  
47 =head2 sync
48  
49 Name : sync
50 Function : answers synchronous requests of asynchronous BioMOBY
51 services; it tries to execute the service; if execution
52 time exceeds a defined timeout, it returns a moby exception
53 suggesting to invoke the service asynchronously.
54 Usage : sub servicename {
55 my $self = shift @_;
56 return $self->sync($func, $timeout, @_);
57 }
58 Args : $func - the subroutine which carries out the service.
59 $timeout - the allowed timeout in seconds.
60 @_ - the parameters received from the client.
61 Returns : a SOAP response containing a MOBY message.
62  
63 =head2 error
64  
65 Name : error
66 Function : answers synchronous requests of asynchronous BioMOBY
67 services; it just returns a moby exception indicating
68 that the service must be invoked asynchronously.
69 Usage : sub servicename {
70 my $self = shift @_;
71 return $self->error(@_);
72 }
73 Args : @_ - the parameters received from the client.
74 Returns : a SOAP response containing a MOBY message.
75  
76 =head2 async
77  
78 Name : async
79 Function : answers asynchronous requests of asynchronous BioMOBY
80 services.
81 Usage : sub servicename_submit {
82 my $self = shift @_;
83 return $self->async($func, @_);
84 }
85 Args : $func - the subroutine which carries out the service.
86 @_ - the parameters received from the client.
87 Returns : a SOAP response containing an EPR.
88  
89 =cut
90  
91 package MOBY::Async::SimpleServer;
92 use strict;
93 use CGI;
94 use XML::LibXML;
95 use POSIX qw(setsid);
96 use MOBY::CommonSubs qw(:all);
97 use MOBY::Async::LSAE;
98 use MOBY::Async::WSRF;
99  
100 use base qw(WSRF::FileBasedMobyResourceLifetimes);
101  
102 use vars qw /$VERSION/;
103 $VERSION = sprintf "%d.%02d", q$Revision: 1.6 $ =~ /: (\d+)\.(\d+)/;
104  
105 #===============================================================================
106 # async_create
107 #
108 # This variable is a subroutine which creates a WS-Resource and returns
109 # an EPR associated to it.
110 #
111 my $async_create = sub {
112 my $class = shift @_;
113 my $envelope = pop @_;
114
115 # Get an identifier for the resource
116 my $ID = WSRF::GSutil::CalGSH_ID();
117 $ENV{ID} = $ID;
118
119 # Create an EndpointReference for the resource
120 my $EPR = WSRF::WS_Address->new();
121  
122 my($query)=CGI->new();
123 my($proto)=($query->https())?'https':'http';
124 my($host)=$query->virtual_host();
125 # This line is needed to fix a bug in CGI library
126 # which only appears when the server is living behind
127 # more than one proxy
128 $host =~ s/^([^,]+),.*/$1/;
129 my($port)=$query->virtual_port();
130 if(($proto eq 'http' && $port eq '80') || ($proto eq 'https' && $port eq '443')) {
131 $port='';
132 } else {
133 $port = ':'.$port;
134 }
135 my($relpath)=$query->script_name();
136 my($virtualrel)=$ENV{'HTTP_VIA'} || $ENV{'HTTP_FORWARDED'} || $ENV{'HTTP_X_FORWARDED_FOR'};
137 if(defined($virtualrel) && $virtualrel =~ /^(?:https?:\/\/[^:\/]+)?(?::[0-9]+)?(\/.*)/) {
138 $relpath=$1;
139 }
140  
141 $EPR->Address("$proto://$host$port$relpath?asyncId=$ID");
142 #$EPR->Address("http://".$ENV{SERVER_NAME}.$ENV{SCRIPT_NAME});
143 $EPR->ReferenceParameters('<wsa:ReferenceParameters><mobyws:ServiceInvocationId xmlns:mobyws="'.$WSRF::Constants::MOBY.'">'.$ENV{ID}.'</mobyws:ServiceInvocationId></wsa:ReferenceParameters>');
144 $EPR = XML::LibXML->new->parse_string($EPR->XML)->getDocumentElement->toString;
145
146 # Write the properties to a file
147 WSRF::File::toFile($ID);
148
149 # Return the EndpointReference
150 return WSRF::Header::header($envelope), SOAP::Data->uri($WSRF::Constants::MOBY)
151 ->name('body' => \SOAP::Data->value(
152 SOAP::Data->type('xml'=>$EPR)
153 )
154 );
155 };
156  
157 #===============================================================================
158 # async_submit
159 #
160 # This variable is a subroutine which submits a batch-call and returns all
161 # status properties.
162 #
163 my $async_submit = sub {
164 my $class = shift @_;
165 my $envelope = pop @_;
166 my ($func, $data) = @_;
167
168 # Get input queryIDs and store them
169 my $ID=$ENV{ID};
170 my $lock = WSRF::MobyFile->new($envelope,$ID);
171 my $inputs = serviceInputParser($data);
172 my @queryIDs = keys %$inputs;
173 $WSRF::WSRP::Private{queryIDs} = \@queryIDs;
174 $lock->toFile();
175
176 # Get moby document
177 my $parser = XML::LibXML->new();
178 my $doc = $parser->parse_string($data);
179 my $moby = $doc->getDocumentElement();
180
181 # Get authority
182 my @mobyContents = ($moby->getChildrenByTagNameNS($WSRF::Constants::MOBY_MESSAGE_NS,'mobyContent'));
183 my $mobyContent = shift(@mobyContents);
184 my $auth = $mobyContent->getAttribute('authority') || $mobyContent->getAttributeNS($WSRF::Constants::MOBY_MESSAGE_NS,'authority');
185
186 # Get mobyData and iterate over them in order to run the service for each one
187 my @mobyData = ($mobyContent->getChildrenByTagNameNS($WSRF::Constants::MOBY_MESSAGE_NS,'mobyData'));
188  
189 foreach my $mobyData (@mobyData) {
190 # This line avoids a serialization bug in XML::LibXML, which probably
191 # is inherited from libxml2
192 $mobyData->setNamespace($WSRF::Constants::MOBY_MESSAGE_NS, $mobyData->prefix(), 0);
193 my $queryID = $mobyData->getAttribute('queryID') || $mobyData->getAttributeNS($WSRF::Constants::MOBY_MESSAGE_NS,'queryID');
194 my $property_pid = "pid_$queryID";
195 my $property_input = "input_$queryID";
196 my $property_status = "status_$queryID";
197 my $property_result = "result_$queryID";
198
199 # Check if service is running or not
200 my $lock = WSRF::MobyFile->new($envelope,$ID);
201 if ($WSRF::WSRP::Private{$property_pid}) {
202 $lock->toFile();
203 } else {
204
205 # Input
206 my $parser = XML::LibXML->new();
207 my $doc = $parser->parse_string(responseHeader($auth).$mobyData->toString().responseFooter());
208 my $input = $doc->getDocumentElement->toString;
209
210 # Fork
211 unless (defined( my $pid = fork() )) {
212
213 #-----------------#
214 # Fork has failed #
215 #-----------------#
216
217 # Status
218 my $status = LSAE::AnalysisEventBlock->new();
219 $status->type(LSAE_STATE_CHANGED_EVENT);
220 $status->previous_state('created');
221 $status->new_state('terminated_by_error');
222 $status->id($queryID);
223
224 # Result
225 my $result;
226 $result = responseHeader($ENV{AUTHURI});
227 $result .= "<serviceNotes xmlns='$WSRF::Constants::MOBY_MESSAGE_NS'><mobyException refQueryID=\'$queryID\' severity=\'error\'>";
228 $result .= "<exceptionCode>701</exceptionCode>";
229 $result .= "<exceptionMessage>Unable to submit job.</exceptionMessage>";
230 $result .= "</mobyException>";
231 $result .= "</serviceNotes>";
232 $result .= simpleResponse('', '', $queryID) . responseFooter();
233 $result = XML::LibXML->new()->parse_string($result)->getDocumentElement()->toString();
234
235 # New properties values
236 $WSRF::WSRP::Private{$property_pid} = '';
237 $WSRF::WSRP::Private{$property_input} = $input;
238 $WSRF::WSRP::ResourceProperties{$property_status} = $status->XML();
239 $WSRF::WSRP::ResourceProperties{$property_result} = $result;
240 $lock->toFile();
241
242 } elsif ( $pid ) {
243
244 #-----------------------------------------------------#
245 # Fork has had success and this is the parent process #
246 #-----------------------------------------------------#
247
248 # Status
249 my $status;
250 if ($WSRF::WSRP::ResourceProperties{$property_status}) {
251
252 # This is not the first execution of the service for this queryID
253 # Previous state is the new state of the previous execution
254 my $old_status = LSAE::AnalysisEventBlock->new($WSRF::WSRP::ResourceProperties{$property_status});
255 $status = LSAE::AnalysisEventBlock->new();
256 $status->type(LSAE_STATE_CHANGED_EVENT);
257 $status->previous_state($old_status->new_state());
258 $status->new_state('created');
259 $status->id($queryID);
260
261 } else {
262
263 # This is the first execution of the service for this queryID
264 $status = LSAE::AnalysisEventBlock->new();
265 $status->type(LSAE_STATE_CHANGED_EVENT);
266 $status->previous_state('created');
267 $status->new_state('created');
268 $status->id($queryID);
269 }
270
271 # New properties values
272 $WSRF::WSRP::Private{$property_pid} = 'undef';
273 $WSRF::WSRP::Private{$property_input} = $input;
274 $WSRF::WSRP::ResourceProperties{$property_status} = $status->XML();
275 $WSRF::WSRP::ResourceProperties{$property_result} = '';
276 $lock->toFile();
277
278 } else {
279
280 #----------------------------------------------------#
281 # Fork has had success and this is the child process #
282 #----------------------------------------------------#
283
284 # Daemonize
285 open STDIN, "/dev/null";
286 open STDOUT, ">/dev/null";
287 open STDERR, ">/dev/null";
288 setsid;
289
290 # Status
291 my $status = LSAE::AnalysisEventBlock->new();
292 $status->type(LSAE_STATE_CHANGED_EVENT);
293 $status->previous_state('created');
294 $status->new_state('running');
295 $status->id($queryID);
296
297 # New properties values
298 $lock = WSRF::MobyFile->new($envelope,$ID);
299 $WSRF::WSRP::Private{$property_pid} = $$;
300 $WSRF::WSRP::ResourceProperties{$property_status} = $status->XML();
301 $WSRF::WSRP::ResourceProperties{$property_result} = '';
302 $lock->toFile();
303
304 # Run service
305 my $result;
306 eval {
307 my $xml = $func->($class, $input);
308 if(UNIVERSAL::isa($xml,'XML::LibXML::Document')) {
309 $result=$xml->getDocumentElement()->toString();
310 } elsif(UNIVERSAL::isa($xml,'XML::LibXML::Node')) {
311 $result=$xml->toString();
312 } else {
313 my $parser = XML::LibXML->new();
314 my $toparse;
315 if(ref(\$xml) eq 'SCALAR') {
316 $toparse=$xml;
317 } elsif(UNIVERSAL::isa($xml,'SOAP::Data')) {
318 $toparse=$xml->value();
319 } else {
320 die "FATAL ERROR: Unable to handle result type ".ref($xml);
321 }
322 my $doc = $parser->parse_string($toparse);
323 $result = $doc->getDocumentElement()->toString();
324 }
325 };
326
327 # Check if there has been errors during service execution
328 unless ($@) {
329
330 # Service has been executed successfully
331
332 # Status
333 $status = LSAE::AnalysisEventBlock->new();
334 $status->type(LSAE_STATE_CHANGED_EVENT);
335 $status->previous_state('running');
336 $status->new_state('completed');
337 $status->id($queryID);
338
339 } else {
340
341 # Service execution has failed
342
343 # Status
344 $status = LSAE::AnalysisEventBlock->new();
345 $status->type(LSAE_STATE_CHANGED_EVENT);
346 $status->previous_state('running');
347 $status->new_state('terminated_by_error');
348 $status->id($queryID);
349
350 # Result
351 $result = responseHeader($ENV{AUTHURI});
352 $result .= "<serviceNotes xmlns='$WSRF::Constants::MOBY_MESSAGE_NS'><mobyException refQueryID=\'$queryID\' severity=\'error\'>";
353 $result .= "<exceptionCode>701</exceptionCode>";
354 $result .= "<exceptionMessage>Error while executing job.</exceptionMessage>";
355 $result .= "</mobyException>";
356 $result .= "</serviceNotes>";
357 $result .= simpleResponse('', '', $queryID) . responseFooter();
358 $result = XML::LibXML->new()->parse_string($result)->getDocumentElement()->toString();
359 }
360
361 # New properties values
362 $lock = WSRF::MobyFile->new($envelope,$ID);
363 $WSRF::WSRP::Private{$property_pid} = '';
364 $WSRF::WSRP::ResourceProperties{$property_status} = $status->XML();
365 $WSRF::WSRP::ResourceProperties{$property_result} = $result;
366 $lock->toFile();
367
368 # Exits the child process
369 exit;
370 }
371 }
372 }
373
374 # Compose response using the status properties
375 $lock = WSRF::MobyFile->new($envelope,$ID);
376 my $ans = '';
377 foreach my $queryID (@queryIDs) {
378 my $property_status = "status_$queryID";
379 $ans .= "<".$WSRF::WSRP::PropertyNamespaceMap->{$property_status}{prefix}.":$property_status";
380 my $ns = defined($WSRF::WSRP::PropertyNamespaceMap->{$property_status}{namespace}) ?
381 " xmlns:".$WSRF::WSRP::PropertyNamespaceMap->{$property_status}{prefix}."=\"".
382 $WSRF::WSRP::PropertyNamespaceMap->{$property_status}{namespace}."\">" :
383 ">";
384 $ans .= $ns;
385 $ans .= $WSRF::WSRP::ResourceProperties{$property_status};
386 $ans .= "</".$WSRF::WSRP::PropertyNamespaceMap->{$property_status}{prefix}.":$property_status>";
387 }
388 $lock->toFile();
389
390 # Return status properties
391 # return WSRF::Header::header($envelope), SOAP::Data->uri($WSRF::Constants::MOBY)
392 # ->name('body' => \SOAP::Data->value(
393 # SOAP::Data->type('xml'=>$ans)
394 # ));
395 return WSRF::Header::header($envelope), SOAP::Data->type('xml'=>$ans);
396 };
397  
398 #===============================================================================
399 # sync
400 #
401 # Answers synchronous requests of asynchronous BioMOBY services.
402 # It tries to execute the service.
403 # If execution time exceeds a defined timeout, it returns a moby exception.
404 #
405 sub sync {
406 my $class = shift @_;
407 my $envelope = pop @_;
408 my ($func, $timeout, $data) = @_;
409
410 my $ans;
411 $SIG{ALRM} = sub { die "timeout exceeded" };
412 eval {
413 alarm $timeout;
414 $ans = $func->($class, $data);
415 alarm 0;
416 };
417
418 if ($@ =~ /timeout exceeded/) {
419 my $exception = '';
420 my $response = '';
421
422 my $inputs = serviceInputParser($data);
423 foreach my $queryID (keys %$inputs) {
424
425 $exception .= "<mobyException refQueryID=\'$queryID\' severity=\'error\'>";
426 $exception .= "<exceptionCode>701</exceptionCode>";
427 $exception .= "<exceptionMessage>Timeout exceeded. Try to invoke the service asynchronously.</exceptionMessage>";
428 $exception .= "</mobyException>";
429
430 $response .= simpleResponse('', '', $queryID);
431 }
432
433 $ans .= responseHeader($ENV{AUTHURI});
434 $ans .= "<serviceNotes xmlns='$WSRF::Constants::MOBY_MESSAGE_NS'>$exception</serviceNotes>";
435 $ans .= $response;
436 $ans .= responseFooter();
437 $ans = SOAP::Data->value($ans)->type('string');
438 }
439
440 return $ans;
441 }
442  
443 #===============================================================================
444 # error
445 #
446 # Answers synchronous requests of asynchronous BioMOBY services
447 # It just returns a moby exception
448 #
449 sub error {
450 my $class = shift @_;
451 my ($data) = @_;
452
453 my $exception = '';
454 my $response = '';
455
456 my $inputs = serviceInputParser($data);
457 foreach my $queryID (keys %$inputs) {
458
459 $exception .= "<mobyException refQueryID=\'$queryID\' severity=\'error\'>";
460 $exception .= "<exceptionCode>701</exceptionCode>";
461 $exception .= "<exceptionMessage>Service must be invoked asynchronously.</exceptionMessage>";
462 $exception .= "</mobyException>";
463
464 $response .= simpleResponse('', '', $queryID);
465 }
466
467 my $ans;
468 $ans .= responseHeader($ENV{AUTHURI});
469 $ans .= "<serviceNotes xmlns='$WSRF::Constants::MOBY_MESSAGE_NS'>$exception</serviceNotes>";
470 $ans .= $response;
471 $ans .= responseFooter();
472
473 return SOAP::Data->value($ans)->type('string');
474 }
475  
476 #===============================================================================
477 # async
478 #
479 # Answers asynchronous requests of asynchronous BioMOBY services
480 #
481 sub async {
482 my $wsa = $async_create->(@_);
483 # The specification says that async always work
484 # so any error related to job creation must
485 # be got using poll.
486 # That's the reason why we are ignoring the returned
487 # value from $async_submit
488 $async_submit->(@_);
489 return $wsa;
490 }
491  
492 #===============================================================================
493 # Destroy
494 #
495 # Redefines WSRF-WSRL Destroy operation in order to kill running processes.
496 #
497 sub Destroy {
498 my ($class, $envelope) = ($_[0], $_[$#_]);
499
500 my $lock = WSRF::MobyFile->new($envelope);
501 $lock->toFile();
502
503 my @notkilled;
504 foreach my $key (keys %WSRF::WSRP::Private) {
505 if (index($key, "pid_") == 0) {
506 my $pid = $WSRF::WSRP::Private{$key};
507 if ($pid) {
508 kill(9, $pid) or push(@notkilled, $pid)
509 }
510 }
511 }
512 WSRF::BaseFaults::die_with_fault( $envelope, (
513 BaseFault => "ResourceNotDestroyedFault",
514 Description => "Could not kill WS-Resource process ".join(", ", @notkilled)
515 ) ) if (scalar(@notkilled));
516
517 return $class->SUPER::Destroy(@_);
518 }
519  
520 1;