[Bio] / FigKernelPackages / ServerThing.pm Repository:
ViewVC logotype

Annotation of /FigKernelPackages/ServerThing.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.85 - (view) (download) (as text)

1 : parrello 1.1 #!/usr/bin/perl -w
2 :    
3 : olson 1.81 #
4 :     # This is a SAS component.
5 :     #
6 : olson 1.79
7 : parrello 1.1 package ServerThing;
8 : olson 1.76 use Data::Dumper;
9 : parrello 1.1 use strict;
10 :     use Tracer;
11 :     use YAML;
12 : parrello 1.85 use YAML::XS;
13 : parrello 1.50 use JSON::Any;
14 : parrello 1.1 use ERDB;
15 :     use TestUtils;
16 : olson 1.79 use Time::HiRes 'gettimeofday';
17 : parrello 1.9 use File::Temp;
18 : parrello 1.10 use ErrorMessage;
19 : parrello 1.1 use CGI;
20 : olson 1.79
21 : olson 1.81 # use bytes;
22 : olson 1.79
23 : parrello 1.9 no warnings qw(once);
24 : parrello 1.1
25 : parrello 1.11 # Maximum number of requests to run per invocation.
26 : olson 1.48 use constant MAX_REQUESTS => 50;
27 : parrello 1.11
28 : olson 1.79 #
29 :     # Carefully import Log4perl.
30 :     #
31 :     BEGIN {
32 :     eval {
33 :     require Log::Log4perl;
34 :     Log::Log4perl->import('get_logger');
35 :     require Try::Tiny;
36 :     Try::Tiny->import;
37 :     };
38 :     };
39 :    
40 : parrello 1.1 =head1 General Server Helper
41 :    
42 :     This package provides a method-- I<RunServer>-- that can be called from a CGI
43 : parrello 1.9 script to perform the duties of a FIG server. RunServer is called with two
44 :     parameters: the name of the server package (e.g. C<SAP> for B<SAP.pm>) and
45 :     the first command-line parameter. The command-line parameter (if defined) will
46 :     be used as the tracing key, and also indicates that the script is being invoked
47 :     from the command line rather than over the web.
48 : parrello 1.1
49 :     =cut
50 :    
51 :     sub RunServer {
52 :     # Get the parameters.
53 : parrello 1.9 my ($serverName, $key) = @_;
54 : parrello 1.25 # Set up tracing. We never do CGI tracing here; the only question is whether
55 :     # or not the caller passed in a tracing key. If he didn't, we use the server
56 :     # name.
57 : parrello 1.32 ETracing($key || $serverName, destType => 'APPEND', level => '0 ServerThing');
58 : parrello 1.9 # Turn off YAML compression, which causes problems with some of our hash keys.
59 :     $YAML::CompressSeries = 0;
60 : parrello 1.13 # Create the server object.
61 : parrello 1.15 Trace("Requiring $serverName for task $$.") if T(3);
62 : parrello 1.13 eval {
63 : chenry 1.60 my $output = $serverName;
64 : devoid 1.74 $output =~ s/::/\//g;
65 : dejongh 1.61 require "$output.pm";
66 : parrello 1.13 };
67 :     # If we have an error, create an error document.
68 :     if ($@) {
69 :     SendError($@, "Could not load server module.");
70 :     } else {
71 :     # Having successfully loaded the server code, we create the object.
72 :     my $serverThing = eval("$serverName" . '->new()');
73 : parrello 1.15 Trace("$serverName object created for task $$.") if T(2);
74 : parrello 1.13 # If we have an error, create an error document.
75 :     if ($@) {
76 :     SendError($@, "Could not start server.");
77 : parrello 1.3 } else {
78 : devoid 1.75 # No error, so now we can process the request. First, get the method list.
79 :     my $methods = $serverThing->methods();
80 : olson 1.79
81 :     my $raw_methods = [];
82 :     if ($serverThing->can("raw_methods"))
83 :     {
84 :     $raw_methods = $serverThing->raw_methods();
85 :     }
86 : devoid 1.75 # Store it in the object so we can use it to validate methods.
87 :     my %methodHash = map { $_ => 1 } @$methods;
88 :     $serverThing->{methods} = \%methodHash;
89 : parrello 1.82 $serverThing->{raw_methods} = { map { $_ => 1 } @$raw_methods };
90 : parrello 1.13 my $cgi;
91 :     if (! defined $key) {
92 :     # No tracing key, so presume we're a web service. Check for Fast CGI.
93 :     if ($ENV{REQUEST_METHOD} eq '') {
94 :     # Count the number of requests.
95 :     my $requests = 0;
96 : devoid 1.75 # warn "Starting fast CGI loop.\n"; ##HACK Trace("Starting Fast CGI loop.") if T(3);
97 : parrello 1.13 # Loop through the fast CGI requests. If we have request throttling,
98 :     # we exit after a maximum number of requests has been exceeded.
99 :     require CGI::Fast;
100 : devoid 1.75 open(SERVER_STDERR, ">&", *STDERR);
101 : parrello 1.23 while ((MAX_REQUESTS == 0 || ++$requests < MAX_REQUESTS) &&
102 :     ($cgi = new CGI::Fast())) {
103 : devoid 1.75 #
104 :     # Remap STDERR. Inside here, our STDERR is a tie to a FCGI::Stream
105 :     # so we need to save it to keep FCGI happy.
106 :     #
107 :     *SAVED_STDERR = *STDERR;
108 :     *STDERR = *SERVER_STDERR;
109 :     my $function = $cgi->param('function') || "<non-functional>"; # (useful if we do tracing in here)
110 :     # warn "Function request is $function in task $$.\n"; ##HACK
111 : parrello 1.13 RunRequest($cgi, $serverThing);
112 : devoid 1.75 # warn "$requests requests complete in fast CGI task $$.\n"; ##HACK Trace("Request $requests complete in task $$.") if T(3);
113 :     *STDERR = *SAVED_STDERR;
114 : parrello 1.13 }
115 : devoid 1.75 # warn "Terminating FastCGI task $$ after $requests requests.\n"; ##HACK Trace("Terminating FastCGI task $$ after $requests requests.") if T(2);
116 :     close(SERVER_STDERR);
117 : parrello 1.13 } else {
118 :     # Here we have a normal web service (non-Fast).
119 :     my $cgi = CGI->new();
120 :     # Check for a source parameter. This gets used as the tracing key.
121 :     $key = $cgi->param('source');
122 :     # Run this request.
123 :     RunRequest($cgi, $serverThing);
124 :     }
125 : parrello 1.6 } else {
126 : parrello 1.13 # We're being invoked from the command line. Use the tracing
127 :     # key to find the parm file and create the CGI object from that.
128 :     my $ih = Open(undef, "<$FIG_Config::temp/$key.parms");
129 :     $cgi = CGI->new($ih);
130 :     # Run this request.
131 :     RunRequest($cgi, $serverThing);
132 : parrello 1.6 }
133 : parrello 1.3 }
134 : parrello 1.1 }
135 : parrello 1.6 }
136 :    
137 : olson 1.76 =head2 RunRabbitMQClient
138 :    
139 :     This routine sets itself up as a FCGI listener for incoming FCGI requests (like
140 : parrello 1.85 RunServer), but instead of processing the requests forwards them to the
141 : olson 1.76 RabbitMQ message broker. For each request, we set up an ephemeral response
142 :     queue for handling the response to the message.
143 :    
144 :     Note that we don't touch the message bodies; they are only decoded on the
145 :     actual messaging processing node.
146 :    
147 :    
148 :     =cut
149 :    
150 :     sub RunRabbitMQClient {
151 :     # Get the parameters.
152 :     my ($serverName, $conf) = @_;
153 :    
154 :     require Net::RabbitMQ;
155 :     require UUID;
156 :     require CGI::Fast;
157 : parrello 1.85
158 : olson 1.76 my $conn = Net::RabbitMQ->new();
159 : parrello 1.85
160 : olson 1.76 $conn->connect($conf->{rabbitmq_host},
161 : olson 1.84 {
162 :     user => $conf->{rabbitmq_user},
163 :     password => $conf->{rabbitmq_password},
164 :     (defined($conf->{rabbitmq_vhost}) ? (vhost => $conf->{rabbitmq_vhost}) : ()),
165 :     });
166 : parrello 1.85
167 : olson 1.76 my $channel = 1;
168 :     $conn->channel_open($channel);
169 : parrello 1.85
170 : olson 1.76 my $exchange_name = "svr.$serverName";
171 : parrello 1.85
172 : olson 1.76 my $queue_name = $conn->queue_declare($channel,'', { durable => 0, exclusive => 1, auto_delete => 1 });
173 :     print "Created $queue_name\n";
174 :    
175 :     my $requests = 0;
176 :     open(SERVER_STDERR, ">&", *STDERR);
177 :     while ((MAX_REQUESTS == 0 || ++$requests < MAX_REQUESTS) &&
178 :     (my $cgi = new CGI::Fast())) {
179 :     #
180 :     # Remap STDERR. Inside here, our STDERR is a tie to a FCGI::Stream
181 :     # so we need to save it to keep FCGI happy.
182 :     #
183 :     *SAVED_STDERR = *STDERR;
184 :     *STDERR = *SERVER_STDERR;
185 :    
186 :     print STDERR "Working...\n";
187 :    
188 :     my $function = $cgi->param('function');
189 :    
190 :     my($uuid, $uuid_str);
191 :    
192 :     UUID::generate($uuid);
193 :     UUID::unparse($uuid, $uuid_str);
194 :    
195 :     my $encoding = $cgi->param('encoding') || 'yaml';
196 :     my $type = $encoding eq 'yaml' ? 'application/yaml' : 'application/json';
197 :    
198 :     print STDERR "publish request to $exchange_name rpc.$function\n";
199 :     $conn->publish($channel, "rpc.$function", $cgi->param('args'),
200 :     { exchange => $exchange_name },
201 :     {
202 :     content_type => $type,
203 :     correlation_id => $uuid_str,
204 :     reply_to => $queue_name,
205 :     });
206 : parrello 1.85
207 : olson 1.76 print STDERR "await resp\n";
208 :     $conn->consume($channel, $queue_name, { no_ack => 1 });
209 : parrello 1.85
210 : olson 1.76 my $msg = $conn->recv();
211 :     print STDERR Dumper($msg);
212 :     print "OK\n";
213 : parrello 1.85
214 : olson 1.76 *STDERR = *SAVED_STDERR;
215 :     }
216 :     # warn "Terminating FastCGI task $$ after $requests requests.\n"; ##HACK Trace("Terminating FastCGI task $$ after $requests requests.") if T(2);
217 :     close(SERVER_STDERR);
218 : parrello 1.85
219 : olson 1.76 }
220 :    
221 : olson 1.84 =head3 RunRabbitMQClientAsync($server_name, $config)
222 :    
223 :     Run the asynchronous FCGI gateway server.
224 :    
225 :     =cut
226 :    
227 : olson 1.76 sub RunRabbitMQClientAsync {
228 :     # Get the parameters.
229 :     my ($serverName, $conf) = @_;
230 :    
231 :     require Net::Async::FastCGI;
232 :     require IO::Handle;
233 :     require IO::Async::Loop;
234 :     require IO::Async::Handle;
235 :     require IO::Async::Timer::Periodic;
236 : olson 1.80 require IO::Async::Signal;
237 : olson 1.76 require Net::RabbitMQ;
238 :     require UUID;
239 :     require CGI::Fast;
240 :    
241 : olson 1.79 my $logger = get_logger("FCGI::RunRabbitMQClientAsync");
242 : parrello 1.85
243 : olson 1.76 my $loop = IO::Async::Loop->new();
244 :    
245 :     my $conn = Net::RabbitMQ->new();
246 : parrello 1.85
247 : olson 1.76 my $rabbit_fd = $conn->connect($conf->{rabbitmq_host},
248 : olson 1.84 {
249 :     user => $conf->{rabbitmq_user},
250 :     password => $conf->{rabbitmq_password},
251 :     (defined($conf->{rabbitmq_vhost}) ? (vhost => $conf->{rabbitmq_vhost}) : ()),
252 :     });
253 : parrello 1.85
254 : olson 1.76 my $channel = 1;
255 :     $conn->channel_open($channel);
256 : parrello 1.85
257 : olson 1.76 my $exchange_name = "svr.$serverName";
258 : parrello 1.85
259 : olson 1.76 my $queue_name = $conn->queue_declare($channel,'', { durable => 0, exclusive => 1, auto_delete => 1 });
260 : olson 1.79 $logger->info("Created $queue_name fcgi_port=$conf->{fcgi_port}");
261 : olson 1.76
262 :     $conn->consume($channel, $queue_name, { no_ack => 1 });
263 :    
264 :     my $waiting = {};
265 : olson 1.79 my $global = { messages => 0,
266 :     queue_size => 0,
267 :     };
268 : olson 1.76 my $rabbit_fh = IO::Handle->new();
269 :     $rabbit_fh->fdopen($rabbit_fd, "r");
270 :    
271 : olson 1.79 my $timer = IO::Async::Timer::Periodic->new(interval => 60,
272 : olson 1.76 on_tick => sub {
273 :     my $last = $global->{last_time};
274 : olson 1.79 my $now = gettimeofday;
275 : olson 1.76 if (defined($last))
276 :     {
277 :     my $int = $now - $last;
278 :     my $rate = $global->{messages} / $int;
279 : olson 1.79 $logger->debug("$rate $global->{queue_size}");
280 :     for my $ent (values %$waiting)
281 :     {
282 :     my $dur = $now - $ent->{start_time};
283 :     my $ip = $ent->{request}->param("REMOTE_ADDR");
284 :     $logger->debug(join("\t", '', $dur, $ip, $ent->{function}));
285 :     }
286 : olson 1.76 }
287 :     $global->{last_time} = $now;
288 :     $global->{messages} = 0;
289 :     });
290 : parrello 1.85
291 : olson 1.76 $timer->start();
292 :     $loop->add($timer);
293 :     my $rabbit_listener = IO::Async::Handle->new(read_handle => $rabbit_fh,
294 :     on_read_ready => sub {
295 : olson 1.84 AsyncRabbitCheck($loop, $channel, $conn, $waiting, $global);
296 : olson 1.76 });
297 :     $loop->add($rabbit_listener);
298 :    
299 :     my $fcgi = Net::Async::FastCGI->new(on_request => sub {
300 :     my($fcgi, $req) = @_;
301 :     $global->{messages}++;
302 : parrello 1.85 AsyncFcgiReq($loop, $fcgi, $req, $channel, $conn, $queue_name,
303 : olson 1.79 $exchange_name, $waiting, $global);
304 : olson 1.76 });
305 : olson 1.81 #
306 :     # This is critical, otherwise we get our bytes munged.
307 :     #
308 :     $fcgi->configure(default_encoding => undef);
309 : parrello 1.85
310 : olson 1.80 for my $signal (qw(HUP INT TERM))
311 :     {
312 :     my $sighandler = IO::Async::Signal->new(name => $signal,
313 :     on_receipt => sub { AsyncSignalHandler($global, $logger, $loop, $fcgi); });
314 :     $loop->add($sighandler);
315 :     }
316 :    
317 : olson 1.76 $loop->add( $fcgi );
318 :    
319 :     $fcgi->listen(service => $conf->{fcgi_port},
320 :     socktype => 'stream',
321 :     host => '0.0.0.0',
322 : olson 1.79 on_resolve_error => sub { $logger->error("Cannot resolve - $_[0]"); },
323 :     on_listen_error => sub { $logger->error("Cannot listen"); },
324 : olson 1.76 );
325 : parrello 1.85
326 : olson 1.80 $global->{idle_notifier_count} = scalar grep { $_->isa("IO::Async::Handle") } $loop->notifiers();
327 :    
328 :     while (1)
329 :     {
330 :     $loop->loop_once();
331 :     if ($global->{request_exit} && $global->{queue_size} == 0)
332 :     {
333 :     my $n = scalar grep { $_->isa("IO::Async::Handle") } $loop->notifiers();
334 :     if ($n <= $global->{idle_notifier_count})
335 :     {
336 :     $logger->info("Final requests have completed, exiting program.");
337 :     return;
338 :     }
339 :     }
340 :     }
341 :     }
342 :    
343 :     sub AsyncSignalHandler
344 :     {
345 :     my($global, $logger, $loop, $fcgi) = @_;
346 :    
347 :     if ($global->{signal_seen})
348 :     {
349 :     $logger->info("AsyncSignalHandler already saw a signal, terminating now");
350 :     exit;
351 :     }
352 :     $logger->info("AsyncSignalHandler handling first signal");
353 : parrello 1.85
354 : olson 1.80 #
355 : parrello 1.85 # Mark for a graceful exit.
356 : olson 1.80 #
357 :    
358 :     $logger->info("Requesting graceful exit");
359 :    
360 :     $global->{signal_seen} = 1;
361 :     $global->{request_exit} = 1;
362 :     # $fcgi->close_read();
363 : olson 1.76 }
364 :    
365 :     sub AsyncRabbitCheck
366 :     {
367 : olson 1.84 my($loop, $channel, $conn, $waiting, $global) = @_;
368 : olson 1.79
369 : olson 1.76 my $msg = $conn->recv();
370 :    
371 : olson 1.79 my $logger = get_logger("FCGI::QueueRead");
372 :     $logger->debug("AsyncRabbitCheck start");
373 :    
374 : olson 1.76 my $corr= $msg->{props}->{correlation_id};
375 :    
376 :     my $slot = delete $waiting->{$corr};
377 :     if ($slot)
378 :     {
379 :     my $req = $slot->{request};
380 : olson 1.79 my $start = $slot->{start_time};
381 : parrello 1.85
382 : olson 1.79 #
383 :     # Unpack body.
384 :     #
385 :     my($code, $msg, $body) = unpack("nN/aN/a", $msg->{body});
386 : olson 1.76
387 : olson 1.79 my $now = gettimeofday;
388 :     my $elap = $now - $start;
389 :     $logger->info(sprintf("Evaluation of method $slot->{function} complete code=$code time=%.6f ip=%s corr=$corr",
390 :     $elap, $req->{params}->{REMOTE_ADDR}));
391 :    
392 :     try {
393 :     $req->print_stdout("Status: $code $msg\r\n" .
394 : olson 1.76 "Content-type: application/octet-stream\r\n" .
395 :     "\r\n");
396 : olson 1.79 $req->print_stdout($body);
397 :     }
398 :     catch {
399 :     $logger->error("Error caught while returning response: $_");
400 : olson 1.83 };
401 : olson 1.81 $req->finish();
402 :     $global->{queue_size}--;
403 : olson 1.76 }
404 :     else
405 :     {
406 : olson 1.79 $logger->error("No matching request found for correlation_id=$corr");
407 : olson 1.76 }
408 :     }
409 :    
410 :     sub AsyncFcgiReq
411 :     {
412 : olson 1.79 my($loop, $fcgi, $req, $channel, $conn, $queue_name, $exchange_name, $waiting, $global) = @_;
413 : parrello 1.85
414 : olson 1.79 my $logger = get_logger("FCGI::Handler");
415 : olson 1.76
416 :     my $params = $req->params;
417 :     my $cgi = CGI->new();
418 :     my $in = $req->read_stdin;
419 :     $cgi->parse_params($in);
420 :    
421 :     my $function = $cgi->param('function');
422 : olson 1.84 my $publish_queue = "rpc.$function";
423 : olson 1.76
424 : olson 1.84 #
425 :     # Inspect the incoming request to see if we have one of the "slow queue"
426 : parrello 1.85 # requests. Currently these are only the blast-based assignment
427 : olson 1.84 # calls using assign_function_to_prot.
428 :     #
429 :     if ($function eq 'assign_function_to_prot' &&
430 :     $cgi->param('-assignToAll'))
431 :     {
432 :     $publish_queue = "rpc_slow.$function";
433 :     }
434 : parrello 1.85
435 : olson 1.76 my($uuid, $uuid_str);
436 : parrello 1.85
437 : olson 1.76 UUID::generate($uuid);
438 :     UUID::unparse($uuid, $uuid_str);
439 : parrello 1.85
440 : olson 1.79 $logger->debug("Request received for $function correlation_id=$uuid_str");
441 :    
442 : olson 1.76 my $encoding = $cgi->param('encoding') || 'yaml';
443 :     my $type = $encoding eq 'yaml' ? 'application/yaml' : 'application/json';
444 : olson 1.79
445 :     my $now = gettimeofday;
446 :    
447 :     my $s = YAML::Dump($params);
448 :     # if ($s =~ /CONTENT/ )
449 :     # {
450 :     # $s = $s . ('-' x (944 - length($s)));
451 :     # }
452 :     my $packed_data = pack("N/aN/a", $s, $in);
453 : olson 1.81 # print "utf s=" . (Encode::is_utf8($s) ? 'YES' : 'NO') . "\n";
454 :     # print "utf in=" . (Encode::is_utf8($in) ? 'YES' : 'NO') . "\n";
455 : parrello 1.85
456 : olson 1.81 # print "pack length " . length($s) . " is_utf=" . (Encode::is_utf8($packed_data) ? 'YES' : 'NO') . "\n";
457 :     # utf8::downgrade($packed_data);
458 :     # use Devel::Peek;
459 : parrello 1.85
460 : olson 1.81 # print Dump($packed_data);
461 : olson 1.84 $conn->publish($channel, $publish_queue,
462 : olson 1.79 $packed_data,
463 : olson 1.76 { exchange => $exchange_name },
464 :     {
465 :     content_type => $type,
466 :     correlation_id => $uuid_str,
467 :     reply_to => $queue_name,
468 :     });
469 : olson 1.79
470 :     $global->{queue_size}++;
471 : parrello 1.85
472 : olson 1.79 $waiting->{$uuid_str} = { request => $req,
473 :     start_time => $now,
474 :     function => $function,
475 :     };
476 : olson 1.76 }
477 :    
478 :     =head2 RunRabbitMQServer
479 :    
480 :     This is the agent code that listens on a queue for incoming requests to
481 : parrello 1.85 process data. We run one of these processes for every core we want to
482 : olson 1.76 do active processing.
483 :    
484 :     =cut
485 :    
486 :     sub RunRabbitMQServer {
487 :     # Get the parameters.
488 :     my ($serverName, $conf) = @_;
489 :    
490 : olson 1.79 my $logger = get_logger("Server");
491 :     $logger->info("RunRabbitMQServer startup");
492 :    
493 : olson 1.76 eval {
494 :     my $output = $serverName;
495 :     $output =~ s/::/\//;
496 :     require "$output.pm";
497 :     };
498 :    
499 :     if ($@) {
500 : olson 1.79 $logger->logdie("Could not load server module $serverName");
501 : olson 1.76 }
502 :     # Having successfully loaded the server code, we create the object.
503 :     my $serverThing = $serverName->new();
504 :    
505 : olson 1.79 my $methodsL = $serverThing->methods;
506 :     my $raw_methodsL = $serverThing->can("raw_methods") ? $serverThing->raw_methods : [];
507 :     my %methods = (methods => 1 );
508 :     my %raw_methods;
509 :     $methods{$_} = 1 for @$methodsL;
510 :     $raw_methods{$_} = 1 for @$raw_methodsL;
511 :    
512 : olson 1.76 require Net::RabbitMQ;
513 :     require UUID;
514 :     require CGI::Fast;
515 : parrello 1.85
516 : olson 1.76 my $conn = Net::RabbitMQ->new();
517 : parrello 1.85
518 : olson 1.76 $conn->connect($conf->{rabbitmq_host},
519 : olson 1.84 {
520 :     user => $conf->{rabbitmq_user},
521 :     password => $conf->{rabbitmq_password},
522 :     (defined($conf->{rabbitmq_vhost}) ? (vhost => $conf->{rabbitmq_vhost}) : ()),
523 :     });
524 : parrello 1.85
525 : olson 1.76 my $channel = 1;
526 :     $conn->channel_open($channel);
527 :    
528 :     $conn->basic_qos($channel, { prefetch_count => 1 });
529 : parrello 1.85
530 : olson 1.76 my $exchange_name = "svr.$serverName";
531 : parrello 1.85
532 : olson 1.76 my $queue_name = "q.$exchange_name";
533 : olson 1.84 my $base = "rpc";
534 :     if ($conf->{slow_queue_listener})
535 :     {
536 :     $base = "rpc_slow";
537 :     $queue_name = "qslow.$exchange_name";
538 :     }
539 : olson 1.76
540 :     $conn->exchange_declare($channel, $exchange_name, { exchange_type => "topic", durable => 1,
541 :     auto_delete => 0 });
542 :    
543 :     $conn->queue_declare($channel, $queue_name, { durable => 1, exclusive => 0, auto_delete => 0 });
544 :    
545 : olson 1.84 $conn->queue_bind($channel, $queue_name, $exchange_name, "$base.*");
546 :    
547 :     $logger->debug("Listening: queue=$queue_name base=$base");
548 : olson 1.76
549 :     $conn->consume($channel, $queue_name, { no_ack => 0 } );
550 :     while (1)
551 :     {
552 : olson 1.79 $logger->debug("Await message");
553 : olson 1.76
554 :     my $msg = $conn->recv();
555 : olson 1.79 $conn->ack($channel, $msg->{delivery_tag});
556 : olson 1.76
557 :     my $key = $msg->{routing_key};
558 :    
559 :     my $args = [];
560 :    
561 : olson 1.84 if ($key !~ /^$base\.(.*)/)
562 : olson 1.76 {
563 : olson 1.79 $logger->error("invalid message key '$key'");
564 :     # $conn->ack($channel, $msg->{delivery_tag});
565 :     next;
566 :     }
567 :     my $method = $1;
568 : parrello 1.85
569 : olson 1.79 my $props = $msg->{props};
570 :     my $encoding = $props->{content_type};
571 :     my $corr = $props->{correlation_id};
572 :     my $reply_to = $props->{reply_to};
573 : parrello 1.85
574 : olson 1.79 my $raw_body = $msg->{body};
575 :    
576 :     my($param_json, $body);
577 :     my $param;
578 :    
579 :     try {
580 :     ($param_json, $body) = unpack("N/aN/a", $raw_body);
581 :     } catch {
582 :     $logger->error("Error unpacking body: $!");
583 :     next;
584 :     };
585 : parrello 1.85
586 : olson 1.79 try {
587 :     $param = YAML::Load($param_json);
588 :     } catch {
589 : olson 1.76
590 : olson 1.79 $logger->error("Error parsing JSON for method $method: $_");
591 :     $param = {};
592 :     };
593 : parrello 1.85
594 : olson 1.79 my $cgi = CGI->new();
595 :     $cgi->parse_params($body);
596 : parrello 1.85
597 : olson 1.79 my @res = ();
598 :     my $err;
599 :     my $enc_res = '';
600 :     my $start = gettimeofday;
601 : olson 1.76
602 : olson 1.79 try {
603 :     if ($raw_methods{$method})
604 :     {
605 :     $logger->debug("Raw evaluation of method $method");
606 :     @res = $serverThing->$method($cgi);
607 :     }
608 :     elsif ($methods{$method})
609 :     {
610 :     $logger->debug("Normal evaluation of method $method");
611 :     my $arg_raw = $cgi->param('args');
612 : parrello 1.85
613 : olson 1.76 if ($encoding eq 'application/json')
614 :     {
615 : olson 1.79 $args = JSON::Any->jsonToObj($arg_raw);
616 : olson 1.76 }
617 :     elsif ($encoding eq 'application/yaml')
618 :     {
619 : olson 1.79 $args = YAML::Load($arg_raw);
620 : olson 1.76 }
621 :     else
622 :     {
623 : olson 1.79 $logger->logwarn("Invalid encoding $encoding");
624 : olson 1.76 $args = [];
625 :     }
626 : olson 1.79 @res = eval { $serverThing->$method($args) };
627 :     }
628 :     else
629 :     {
630 :     $logger->error("No method defined for $method");
631 :     die new ServerReturn(500, "Undefined method", "No method defined for $method");
632 :     }
633 :     my $end = gettimeofday;
634 :     my $elap = $end - $start;
635 :     $logger->info(sprintf("Evaluation of method $method complete time=%.6f corr=$corr", $elap));
636 : parrello 1.85
637 : olson 1.76
638 :     if ($encoding eq 'application/json')
639 :     {
640 : olson 1.79 $enc_res = JSON::Any->objToJson(@res);
641 : olson 1.76 }
642 :     elsif ($encoding eq 'application/yaml')
643 :     {
644 : olson 1.79 $enc_res = YAML::Dump(@res);
645 :     }
646 :     }
647 :     catch
648 :     {
649 :     $logger->error("Error encountered in method evaluation: $_");
650 :     if (ref($_))
651 :     {
652 :     $err = $_;
653 :     }
654 :     else
655 :     {
656 :     $err = new ServerReturn(500, "Evaluation error", $_);
657 : olson 1.76 }
658 :     };
659 : olson 1.79 # print Dumper($encoding, $enc_res);
660 :    
661 :     #
662 :     # The returned message consists of a response code, response message,
663 :     # and the body of the response. These map currently to the HTTP return code,
664 :     # the short message, and the body of the reply. The FCGI management code that
665 :     # receives these responses does not touch the data in the body.
666 :     #
667 :    
668 :     my $ret;
669 : parrello 1.85
670 : olson 1.79 if ($err)
671 :     {
672 :     $ret = $err;
673 :     }
674 :     else
675 :     {
676 :     $ret = ServerReturn->new(200, "OK", $enc_res);
677 :     }
678 :    
679 :     $conn->publish($channel, $reply_to, $ret->package_response(), { exchange => '' }, { correlation_id => $corr });
680 : olson 1.76
681 :     }
682 :     }
683 :    
684 : parrello 1.6
685 : parrello 1.9 =head2 Server Utility Methods
686 :    
687 :     The methods in this section are utilities of general use to the various
688 :     server modules.
689 :    
690 : parrello 1.21 =head3 AddSubsystemFilter
691 :    
692 : parrello 1.52 ServerThing::AddSubsystemFilter(\$filter, $args, $roles);
693 : parrello 1.21
694 :     Add subsystem filtering information to the specified query filter clause
695 :     based on data in the argument hash. The argument hash will be checked for
696 : parrello 1.85 the C<-usable> parameter, which includes or excludes unusuable subsystems,
697 : parrello 1.22 the C<-exclude> parameter, which lists types of subsystems that should be
698 : parrello 1.52 excluded, and the C<-aux> parameter, which filters on auxiliary roles.
699 : parrello 1.21
700 :     =over 4
701 :    
702 :     =item filter
703 :    
704 :     Reference to the current filter string. If additional filtering is required,
705 :     this string will be updated.
706 :    
707 :     =item args
708 :    
709 :     Reference to the parameter hash for the current server call. This hash will
710 : parrello 1.22 be examined for the C<-usable> and C<-exclude> parameters.
711 : parrello 1.21
712 : parrello 1.52 =item roles
713 :    
714 :     If TRUE, role filtering will be applied. In this case, the default action
715 :     is to exclude auxiliary roles unless C<-aux> is TRUE.
716 :    
717 : parrello 1.21 =back
718 :    
719 :     =cut
720 :    
721 :     use constant SS_TYPE_EXCLUDE_ITEMS => { 'cluster-based' => 1,
722 :     experimental => 1,
723 :     private => 1 };
724 :    
725 :     sub AddSubsystemFilter {
726 :     # Get the parameters.
727 : parrello 1.52 my ($filter, $args, $roles) = @_;
728 : parrello 1.21 # We'll put the new filter stuff in here.
729 :     my @newFilters;
730 :     # Unless unusable subsystems are desired, we must add a clause to the filter.
731 : parrello 1.22 # The default is that only usable subsystems are included.
732 :     my $usable = 1;
733 :     # This default can be overridden by the "-usable" parameter.
734 :     if (exists $args->{-usable}) {
735 :     $usable = $args->{-usable};
736 :     }
737 :     # If we're restricting to usable subsystems, add a filter to that effect.
738 :     if ($usable) {
739 : parrello 1.21 push @newFilters, "Subsystem(usable) = 1";
740 :     }
741 :     # Check for exclusion filters.
742 :     my $exclusions = ServerThing::GetIdList(-exclude => $args, 1);
743 :     for my $exclusion (@$exclusions) {
744 :     if (! SS_TYPE_EXCLUDE_ITEMS->{$exclusion}) {
745 :     Confess("Invalid exclusion type \"$exclusion\".");
746 :     } else {
747 :     # Here we have to exclude subsystems of the specified type.
748 :     push @newFilters, "Subsystem($exclusion) = 0";
749 :     }
750 :     }
751 : parrello 1.52 # Check for role filtering.
752 :     if ($roles) {
753 :     # Here, we filter out auxiliary roles unless the user requests
754 :     # them.
755 :     if (! $args->{-aux}) {
756 :     push @newFilters, "Includes(auxiliary) = 0"
757 :     }
758 :     }
759 : parrello 1.21 # Do we need to update the incoming filter?
760 :     if (@newFilters) {
761 :     # Yes. If the incoming filter is nonempty, push it onto the list
762 :     # so it gets included in the result.
763 :     if ($$filter) {
764 :     push @newFilters, $$filter;
765 :     }
766 :     # Put all the filters together to form the new filter.
767 :     $$filter = join(" AND ", @newFilters);
768 : parrello 1.26 Trace("Subsystem filter is $$filter.") if T(ServerUtilities => 3);
769 : parrello 1.21 }
770 :     }
771 :    
772 :    
773 :    
774 : parrello 1.9 =head3 GetIdList
775 :    
776 : parrello 1.19 my $ids = ServerThing::GetIdList($name => $args, $optional);
777 : parrello 1.9
778 :     Get a named list of IDs from an argument structure. If the IDs are
779 :     missing, or are not a list, an error will occur.
780 :    
781 :     =over 4
782 :    
783 :     =item name
784 :    
785 :     Name of the argument structure member that should contain the ID list.
786 :    
787 :     =item args
788 :    
789 :     Argument structure from which the ID list is to be extracted.
790 :    
791 : parrello 1.19 =item optional (optional)
792 :    
793 :     If TRUE, then a missing value will not generate an error. Instead, an empty list
794 :     will be returned. The default is FALSE.
795 :    
796 : parrello 1.9 =item RETURN
797 :    
798 :     Returns a reference to a list of IDs taken from the argument structure.
799 :    
800 :     =back
801 :    
802 :     =cut
803 :    
804 :     sub GetIdList {
805 :     # Get the parameters.
806 : parrello 1.19 my ($name, $args, $optional) = @_;
807 : parrello 1.35 # Declare the return variable.
808 :     my $retVal;
809 : parrello 1.32 # Check the argument format.
810 : parrello 1.35 if (! defined $args && $optional) {
811 :     # Here there are no parameters, but the arguments are optional so it's
812 :     # okay.
813 :     $retVal = [];
814 :     } elsif (ref $args ne 'HASH') {
815 :     # Here we have an invalid parameter structure.
816 : parrello 1.32 Confess("No '$name' parameter present.");
817 : parrello 1.35 } else {
818 :     # Here we have a hash with potential parameters in it. Try to get the
819 :     # IDs from the argument structure.
820 :     $retVal = $args->{$name};
821 :     # Was a member found?
822 :     if (! defined $retVal) {
823 :     # No. If we're optional, return an empty list; otherwise throw an error.
824 :     if ($optional) {
825 :     $retVal = [];
826 :     } else {
827 :     Confess("No '$name' parameter found.");
828 :     }
829 : parrello 1.19 } else {
830 : parrello 1.35 # Here we found something. Get the parameter type. We want a list reference.
831 :     # If it's a scalar, we'll convert it to a singleton list. If it's anything
832 :     # else, it's an error.
833 :     my $type = ref $retVal;
834 :     if (! $type) {
835 :     $retVal = [$retVal];
836 :     } elsif ($type ne 'ARRAY') {
837 :     Confess("The '$name' parameter must be a list.");
838 :     }
839 : parrello 1.19 }
840 : parrello 1.9 }
841 :     # Return the result.
842 :     return $retVal;
843 :     }
844 :    
845 :    
846 :     =head3 RunTool
847 :    
848 :     ServerThing::RunTool($name => $cmd);
849 :    
850 :     Run a command-line tool. A non-zero return value from the tool will cause
851 :     a fatal error, and the tool's error log will be traced.
852 :    
853 :     =over 4
854 :    
855 :     =item name
856 :    
857 :     Name to give to the tool in the error output.
858 :    
859 :     =item cmd
860 :    
861 :     Command to use for running the tool. This should be the complete command line.
862 :     The command should not contain any fancy piping, though it may redirect the
863 :     standard input and output. The command will be modified by this method to
864 :     redirect the error output to a temporary file.
865 :    
866 :     =back
867 :    
868 :     =cut
869 :    
870 :     sub RunTool {
871 :     # Get the parameters.
872 :     my ($name, $cmd) = @_;
873 :     # Compute the log file name.
874 :     my $errorLog = "$FIG_Config::temp/errors$$.log";
875 :     # Execute the command.
876 : parrello 1.26 Trace("Executing command: $cmd") if T(ServerUtilities => 3);
877 : parrello 1.9 my $res = system("$cmd 2> $errorLog");
878 : parrello 1.26 Trace("Return from $name tool is $res.") if T(ServerUtilities => 3);
879 : parrello 1.9 # Check the result code.
880 :     if ($res != 0) {
881 :     # We have an error. If tracing is on, trace it.
882 : parrello 1.26 if (T(ServerUtilities => 1)) {
883 : parrello 1.9 TraceErrorLog($name, $errorLog);
884 :     }
885 :     # Delete the error log.
886 :     unlink $errorLog;
887 :     # Confess the error.
888 : parrello 1.10 Confess("$name command failed with error code $res.");
889 : parrello 1.9 } else {
890 :     # Everything worked. Trace the error log if necessary.
891 : parrello 1.26 if (T(ServerUtilities => 3) && -s $errorLog) {
892 : parrello 1.9 TraceErrorLog($name, $errorLog);
893 :     }
894 :     # Delete the error log if there is one.
895 :     unlink $errorLog;
896 :     }
897 :     }
898 :    
899 : parrello 1.56 =head3 ReadCountVector
900 :    
901 :     my $vector = ServerThing::ReadCountVector($qh, $field, $rawFlag);
902 :    
903 :     Extract a count vector from a query. The query can contain zero or more results,
904 :     and the vectors in the specified result field of the query must be concatenated
905 :     together in order. This method is optimized for the case (expected to be most
906 :     common) where there is only one result.
907 :    
908 :     =over 4
909 :    
910 :     =item qh
911 :    
912 :     Handle for the query from which results are to be extracted.
913 :    
914 :     =item field
915 :    
916 :     Name of the field containing the count vectors.
917 :    
918 :     =item rawFlag
919 :    
920 :     TRUE if the vector is to be returned as a raw string, FALSE if it is to be returned
921 :     as reference to a list of numbers.
922 :    
923 :     =item RETURN
924 :    
925 :     Returns the desired vector, either encoded as a string or as a reference to a list
926 :     of numbers.
927 :    
928 :     =back
929 :    
930 :     =cut
931 :    
932 :     sub ReadCountVector {
933 :     # Get the parameters.
934 :     my ($qh, $field, $rawFlag) = @_;
935 :     # Declare the return variable.
936 :     my $retVal;
937 :     # Loop through the query results.
938 :     while (my $resultRow = $qh->Fetch()) {
939 :     # Get this vector.
940 :     my ($levelVector) = $resultRow->Value($field, $rawFlag);
941 :     # Is this the first result?
942 :     if (! defined $retVal) {
943 :     # Yes. Assign the result directly.
944 :     $retVal = $levelVector;
945 :     } elsif ($rawFlag) {
946 :     # This is a second result and the vectors are coded as strings.
947 :     $retVal .= $levelVector;
948 :     } else {
949 :     # This is a second result and the vectors are coded as array references.
950 :     push @$retVal, @$levelVector;
951 :     }
952 :     }
953 :     # Return the result.
954 :     return $retVal;
955 :     }
956 :    
957 : parrello 1.58 =head3 ChangeDB
958 :    
959 :     ServerThing::ChangeDB($thing, $newDbName);
960 :    
961 :     Change the sapling database used by this server. The old database will be closed and a
962 :     new one attached.
963 :    
964 :     =over 4
965 :    
966 :     =item newDbName
967 :    
968 :     Name of the new Sapling database on which this server should operate. If omitted, the
969 :     default database will be used.
970 :    
971 :     =back
972 :    
973 :     =cut
974 :    
975 :     sub ChangeDB {
976 :     # Get the parameters.
977 :     my ($thing, $newDbName) = @_;
978 :     # Default the db-name if it's not specified.
979 :     if (! defined $newDbName) {
980 :     $newDbName = $FIG_Config::saplingDB;
981 :     }
982 :     # Check to see if we really need to change.
983 :     my $oldDB = $thing->{db};
984 :     if (! defined $oldDB || $oldDB->dbName() ne $newDbName) {
985 :     # We need a new sapling.
986 :     require Sapling;
987 :     my $newDB = Sapling->new(dbName => $newDbName);
988 :     $thing->{db} = $newDB;
989 :     }
990 :     }
991 :    
992 : parrello 1.36
993 : parrello 1.37 =head2 Gene Correspondence File Methods
994 : parrello 1.36
995 : parrello 1.37 These methods relate to gene correspondence files, which are generated by the
996 :     L<svr_corresponding_genes.pl> script. Correspondence files are cached in the
997 :     organism cache (I<$FIG_Config::orgCache>) directory. Eventually they will be
998 :     copied into the organism directories themselves. At that point, the code below
999 :     will be modified to check the organism directories first and use the cache
1000 :     directory if no file is found there.
1001 :    
1002 :     A gene correspondence file contains correspondences from a source genome to a
1003 :     target genome. Most such correspondences are bidirectional best hits. A unidirectional
1004 :     best hit may exist from the source genome to the target genome or in the reverse
1005 :     direction from the targtet genome to the source genome. The cache directory itself
1006 :     is divided into subdirectories by organism. The subdirectory has the source genome
1007 :     name and the files themselves are named by the target genome.
1008 :    
1009 :     Some of the files are invalid and will be erased when they are found. A file is
1010 :     considered invalid if it has a non-numeric value in a numeric column or if it
1011 :     does not have any unidirectional hits from the target genome to the source
1012 :     genome.
1013 :    
1014 :     The process of managing the correspondence files is tricky and dangerous because
1015 :     of the possibility of race conditions. It can take several minutes to generate a
1016 :     file, and if two processes try to generate the same file at the same time we need
1017 :     to make sure they don't step on each other.
1018 :    
1019 :     In stored files, the source genome ID is always lexically lower than the target
1020 :     genome ID. If a correspondence in the reverse direction is desired, the converse
1021 :     file is found and the contents flipped automatically as they are read. So, the
1022 :     correspondence from B<360108.3> to B<100226.1> would be found in a file with the
1023 :     name B<360108.3> in the directory for B<100226.1>. Since this file actually has
1024 :     B<100226.1> as the source and B<360108.3> as the target, the columns are
1025 :     re-ordered and the arrows reversed before the file contents are passed to the
1026 :     caller.
1027 :    
1028 :     =head4 Gene Correspondence List
1029 :    
1030 :     A gene correspondence file contains 18 columns. These are usually packaged as
1031 :     a reference to list of lists. Each sub-list has the following format.
1032 :    
1033 :     =over 4
1034 :    
1035 :     =item 0
1036 :    
1037 :     The ID of a PEG in genome 1.
1038 :    
1039 :     =item 1
1040 :    
1041 :     The ID of a PEG in genome 2 that is our best estimate of a "corresponding gene".
1042 :    
1043 :     =item 2
1044 :    
1045 :     Count of the number of pairs of matching genes were found in the context.
1046 :    
1047 :     =item 3
1048 :    
1049 :     Pairs of corresponding genes from the contexts.
1050 :    
1051 :     =item 4
1052 :    
1053 :     The function of the gene in genome 1.
1054 :    
1055 :     =item 5
1056 :    
1057 :     The function of the gene in genome 2.
1058 :    
1059 :     =item 6
1060 :    
1061 :     Comma-separated list of aliases for the gene in genome 1 (any protein with an
1062 :     identical sequence is considered an alias, whether or not it is actually the
1063 :     name of the same gene in the same genome).
1064 :    
1065 :     =item 7
1066 :    
1067 :     Comma-separated list of aliases for the gene in genome 2 (any protein with an
1068 :     identical sequence is considered an alias, whether or not it is actually the
1069 :     name of the same gene in the same genome).
1070 :    
1071 :     =item 8
1072 :    
1073 :     Bi-directional best hits will contain "<=>" in this column; otherwise, "->" will appear.
1074 :    
1075 :     =item 9
1076 :    
1077 :     Percent identity over the region of the detected match.
1078 :    
1079 :     =item 10
1080 :    
1081 :     The P-score for the detected match.
1082 :    
1083 :     =item 11
1084 :    
1085 :     Beginning match coordinate in the protein encoded by the gene in genome 1.
1086 :    
1087 :     =item 12
1088 :    
1089 :     Ending match coordinate in the protein encoded by the gene in genome 1.
1090 :    
1091 :     =item 13
1092 :    
1093 :     Length of the protein encoded by the gene in genome 1.
1094 :    
1095 :     =item 14
1096 :    
1097 :     Beginning match coordinate in the protein encoded by the gene in genome 2.
1098 :    
1099 :     =item 15
1100 :    
1101 :     Ending match coordinate in the protein encoded by the gene in genome 2.
1102 :    
1103 :     =item 16
1104 :    
1105 :     Length of the protein encoded by the gene in genome 2.
1106 :    
1107 :     =item 17
1108 :    
1109 :     Bit score for the match. Divide by the length of the longer PEG to get
1110 :     what we often refer to as a "normalized bit score".
1111 :    
1112 : devoid 1.75 =item 18 (optional)
1113 :    
1114 :     Clear-correspondence indicator. If present, will be C<1> if the correspondence is a
1115 :     clear bidirectional best hit (no similar candidates) and C<0> otherwise.
1116 :    
1117 : parrello 1.37 =back
1118 :    
1119 :     In the actual files, there will also be reverse correspondences indicated by a
1120 :     back-arrow ("<-") in item (8). The output returned by the servers, however,
1121 :     is filtered so that only forward correspondences occur. If a converse file
1122 :     is used, the columns are re-ordered and the arrows reversed so that it looks
1123 :     correct.
1124 :    
1125 :     =cut
1126 :    
1127 :     # hash for reversing the arrows
1128 :     use constant ARROW_FLIP => { '->' => '<-', '<=>' => '<=>', '<-' => '->' };
1129 :     # list of columns that contain numeric values that need to be validated
1130 :     use constant NUM_COLS => [2,9,10,11,12,13,14,15,16,17];
1131 :    
1132 :     =head3 CheckForGeneCorrespondenceFile
1133 :    
1134 :     my ($fileName, $converse) = ServerThing::CheckForGeneCorrespondenceFile($genome1, $genome2);
1135 :    
1136 :     Try to find a gene correspondence file for the specified genome pairing. If the
1137 :     file exists, its name and an indication of whether or not it is in the correct
1138 :     direction will be returned.
1139 : parrello 1.36
1140 :     =over 4
1141 :    
1142 :     =item genome1
1143 :    
1144 : parrello 1.37 Source genome for the desired correspondence.
1145 : parrello 1.36
1146 :     =item genome2
1147 :    
1148 : parrello 1.37 Target genome for the desired correspondence.
1149 : parrello 1.36
1150 :     =item RETURN
1151 :    
1152 : parrello 1.37 Returns a two-element list. The first element is the name of the file containing the
1153 :     correspondence, or C<undef> if the file does not exist. The second element is TRUE
1154 :     if the correspondence would be forward or FALSE if the file needs to be flipped.
1155 : parrello 1.36
1156 :     =back
1157 :    
1158 :     =cut
1159 :    
1160 : parrello 1.37 sub CheckForGeneCorrespondenceFile {
1161 : parrello 1.36 # Get the parameters.
1162 :     my ($genome1, $genome2) = @_;
1163 : parrello 1.37 # Declare the return variables.
1164 :     my ($fileName, $converse);
1165 :     # Determine the ordering of the genome IDs.
1166 :     my ($corrFileName, $genomeA, $genomeB) = ComputeCorrespondenceFileName($genome1, $genome2);
1167 :     $converse = ($genomeA ne $genome1);
1168 :     # Look for a file containing the desired correspondence. (The code to check for a
1169 :     # pre-computed file in the organism directories is currently turned off, because
1170 :     # these files are all currently invalid.)
1171 :     my $testFileName = "$FIG_Config::organisms/$genomeA/CorrToReferenceGenomes/$genomeB";
1172 :     if (0 && -f $testFileName) {
1173 : parrello 1.36 # Use the pre-computed file.
1174 : parrello 1.44 Trace("Using pre-computed file $fileName for genome correspondence.") if T(Corr => 3);
1175 : parrello 1.37 $fileName = $testFileName;
1176 :     } elsif (-f $corrFileName) {
1177 :     $fileName = $corrFileName;
1178 : parrello 1.44 Trace("Using cached file $fileName for genome correspondence.") if T(Corr => 3);
1179 : parrello 1.37 }
1180 :     # Return the result.
1181 :     return ($fileName, $converse);
1182 :     }
1183 :    
1184 :    
1185 :     =head3 ComputeCorrespondenceFileName
1186 :    
1187 :     my ($fileName, $genomeA, $genomeB) = ServerThing::ComputeCorrespondenceFileName($genome1, $genome2);
1188 :    
1189 :     Compute the name to be given to a genome correspondence file in the organism cache
1190 :     and return the source and target genomes that would be in it.
1191 :    
1192 :     =over 4
1193 :    
1194 :     =item genome1
1195 :    
1196 :     Source genome for the desired correspondence.
1197 :    
1198 :     =item genome2
1199 :    
1200 :     Target genome for the desired correspondence.
1201 :    
1202 :     =item RETURN
1203 :    
1204 :     Returns a three-element list. The first element is the name of the file to contain the
1205 :     correspondence, the second element is the name of the genome that would act as the
1206 :     source genome in the file, and the third element is the name of the genome that would
1207 :     act as the target genome in the file.
1208 :    
1209 :     =back
1210 :    
1211 :     =cut
1212 :    
1213 :     sub ComputeCorrespondenceFileName {
1214 :     # Get the parameters.
1215 :     my ($genome1, $genome2) = @_;
1216 :     # Declare the return variables.
1217 :     my ($fileName, $genomeA, $genomeB);
1218 :     # Determine the ordering of the genome IDs.
1219 : parrello 1.41 if (MustFlipGenomeIDs($genome1, $genome2)) {
1220 : parrello 1.43 ($genomeA, $genomeB) = ($genome2, $genome1);
1221 :     } else {
1222 : parrello 1.37 ($genomeA, $genomeB) = ($genome1, $genome2);
1223 :     }
1224 :     # Insure the source organism has a subdirectory in the organism cache.
1225 : parrello 1.47 my $orgDir = ComputeCorrespondenceDirectory($genomeA);
1226 : parrello 1.37 # Compute the name of the correspondence file for the appropriate target genome.
1227 :     $fileName = "$orgDir/$genomeB";
1228 :     # Return the results.
1229 :     return ($fileName, $genomeA, $genomeB);
1230 :     }
1231 :    
1232 :    
1233 : parrello 1.47 =head3 ComputeCorresopndenceDirectory
1234 :    
1235 :     my $dirName = ServerThing::ComputeCorrespondenceDirectory($genome);
1236 :    
1237 :     Return the name of the directory that would contain the correspondence files
1238 :     for the specified genome.
1239 :    
1240 :     =over 4
1241 :    
1242 :     =item genome
1243 :    
1244 :     ID of the genome whose correspondence file directory is desired.
1245 :    
1246 :     =item RETURN
1247 :    
1248 :     Returns the name of the directory of interest.
1249 :    
1250 :     =back
1251 :    
1252 :     =cut
1253 :    
1254 :     sub ComputeCorrespondenceDirectory {
1255 :     # Get the parameters.
1256 :     my ($genome) = @_;
1257 :     # Insure the source organism has a subdirectory in the organism cache.
1258 :     my $retVal = "$FIG_Config::orgCache/$genome";
1259 :     Tracer::Insure($retVal, 0777);
1260 :     # Return it.
1261 :     return $retVal;
1262 :     }
1263 :    
1264 :    
1265 : parrello 1.37 =head3 CreateGeneCorrespondenceFile
1266 :    
1267 :     my ($fileName, $converse) = ServerThing::CheckForGeneCorrespondenceFile($genome1, $genome2);
1268 :    
1269 :     Create a new gene correspondence file in the organism cache for the specified
1270 :     genome correspondence. The name of the new file will be returned along with
1271 :     an indicator of whether or not it is in the correct direction.
1272 :    
1273 :     =over 4
1274 :    
1275 :     =item genome1
1276 :    
1277 :     Source genome for the desired correspondence.
1278 :    
1279 :     =item genome2
1280 :    
1281 :     Target genome for the desired correspondence.
1282 :    
1283 :     =item RETURN
1284 :    
1285 :     Returns a two-element list. The first element is the name of the file containing the
1286 :     correspondence, or C<undef> if an error occurred. The second element is TRUE
1287 :     if the correspondence would be forward or FALSE if the file needs to be flipped.
1288 :    
1289 :     =back
1290 :    
1291 :     =cut
1292 :    
1293 :     sub CreateGeneCorrespondenceFile {
1294 :     # Get the parameters.
1295 :     my ($genome1, $genome2) = @_;
1296 :     # Declare the return variables.
1297 :     my ($fileName, $converse);
1298 :     # Compute the ultimate name for the correspondence file.
1299 :     my ($corrFileName, $genomeA, $genomeB) = ComputeCorrespondenceFileName($genome1, $genome2);
1300 :     $converse = ($genome1 ne $genomeA);
1301 :     # Generate a temporary file name in the same directory. We'll build the temporary
1302 :     # file and then rename it when we're done.
1303 :     my $tempFileName = "$corrFileName.$$.tmp";
1304 :     # This will be set to FALSE if we detect an error.
1305 :     my $fileOK = 1;
1306 :     # The file handles will be put in here.
1307 :     my ($ih, $oh);
1308 :     # Protect from errors.
1309 :     eval {
1310 :     # Open the temporary file for output.
1311 :     $oh = Open(undef, ">$tempFileName");
1312 :     # Open a pipe to get the correspondence data.
1313 :     $ih = Open(undef, "$FIG_Config::bin/svr_corresponding_genes -u localhost $genomeA $genomeB |");
1314 :     Trace("Creating correspondence file for $genomeA to $genomeB in temporary file $tempFileName.") if T(3);
1315 :     # Copy the pipe date into the temporary file.
1316 :     while (! eof $ih) {
1317 :     my $line = <$ih>;
1318 :     print $oh $line;
1319 :     }
1320 :     # Close both files. If the close fails we need to know: it means there was a pipe
1321 :     # error.
1322 :     $fileOK &&= close $ih;
1323 :     $fileOK &&= close $oh;
1324 :     };
1325 :     if ($@) {
1326 :     # Here a fatal error of some sort occurred. We need to force the files closed.
1327 :     close $ih if $ih;
1328 :     close $oh if $oh;
1329 :     } elsif ($fileOK) {
1330 :     # Here everything worked. Try to rename the temporary file to the real
1331 :     # file name.
1332 :     if (rename $tempFileName, $corrFileName) {
1333 :     # Everything is ok, fix the permissions and return the file name.
1334 :     chmod 0664, $corrFileName;
1335 :     $fileName = $corrFileName;
1336 : parrello 1.44 Trace("Created correspondence file $fileName.") if T(Corr => 3);
1337 : parrello 1.37 }
1338 :     }
1339 :     # If the temporary file exists, delete it.
1340 :     if (-f $tempFileName) {
1341 :     unlink $tempFileName;
1342 :     }
1343 :     # Return the results.
1344 :     return ($fileName, $converse);
1345 :     }
1346 :    
1347 :    
1348 : parrello 1.41 =head3 MustFlipGenomeIDs
1349 :    
1350 :     my $converse = ServerThing::MustFlipGenomeIDs($genome1, $genome2);
1351 :    
1352 :     Return TRUE if the specified genome IDs are out of order. When genome IDs are out of
1353 :     order, they are stored in the converse order in correspondence files on the server.
1354 :     This is a simple method that allows the caller to check for the need to flip.
1355 :    
1356 :     =over 4
1357 :    
1358 :     =item genome1
1359 :    
1360 :     ID of the proposed source genome.
1361 :    
1362 :     =item genome2
1363 :    
1364 :     ID of the proposed target genome.
1365 :    
1366 :     =item RETURN
1367 :    
1368 :     Returns TRUE if the first genome would be stored on the server as a target, FALSE if
1369 :     it would be stored as a source.
1370 :    
1371 : parrello 1.55 =back
1372 :    
1373 : parrello 1.41 =cut
1374 :    
1375 :     sub MustFlipGenomeIDs {
1376 :     # Get the parameters.
1377 :     my ($genome1, $genome2) = @_;
1378 :     # Return an indication.
1379 :     return ($genome1 gt $genome2);
1380 :     }
1381 :    
1382 :    
1383 : parrello 1.37 =head3 ReadGeneCorrespondenceFile
1384 :    
1385 : parrello 1.40 my $list = ServerThing::ReadGeneCorrespondenceFile($fileName, $converse, $all);
1386 : parrello 1.37
1387 :     Return the contents of the specified gene correspondence file in the form of
1388 :     a list of lists, with backward correspondences filtered out. If the file is
1389 :     for the converse of the desired correspondence, the columns will be reordered
1390 :     automatically so that it looks as if the file were designed for the proper
1391 :     direction.
1392 :    
1393 :     =over 4
1394 :    
1395 :     =item fileName
1396 :    
1397 :     The name of the gene correspondence file to read.
1398 :    
1399 :     =item converse (optional)
1400 :    
1401 :     TRUE if the file is for the converse of the desired correspondence, else FALSE.
1402 :     If TRUE, the file columns will be reorderd automatically. The default is FALSE,
1403 :     meaning we want to use the file as it appears on disk.
1404 :    
1405 : parrello 1.40 =item all (optional)
1406 :    
1407 :     TRUE if backward unidirectional correspondences should be included in the output.
1408 :     The default is FALSE, in which case only forward and bidirectional correspondences
1409 :     are included.
1410 :    
1411 : parrello 1.37 =item RETURN
1412 :    
1413 :     Returns a L</Gene Correspondence List> in the form of a reference to a list of lists.
1414 :     If the file's contents are invalid or an error occurs, an undefined value will be
1415 :     returned.
1416 :    
1417 :     =back
1418 :    
1419 :     =cut
1420 :    
1421 :     sub ReadGeneCorrespondenceFile {
1422 :     # Get the parameters.
1423 : parrello 1.40 my ($fileName, $converse, $all) = @_;
1424 : parrello 1.37 # Declare the return variable. We will only put something in here if we are
1425 :     # completely successful.
1426 :     my $retVal;
1427 :     # This value will be set to 1 if an error is detected.
1428 :     my $error = 0;
1429 :     # Try to open the file.
1430 :     my $ih;
1431 :     Trace("Reading correspondence file $fileName.") if T(3);
1432 :     if (! open $ih, "<$fileName") {
1433 :     # Here the open failed, so we have an error.
1434 : parrello 1.44 Trace("Failed to open gene correspondence file $fileName: $!") if T(Corr => 1);
1435 : parrello 1.37 $error = 1;
1436 :     }
1437 :     # The gene correspondence list will be built in here.
1438 :     my @corrList;
1439 :     # This variable will be set to TRUE if we find a reverse correspondence somewhere
1440 :     # in the file. Not finding one is an error.
1441 :     my $reverseFound = 0;
1442 :     # Loop until we hit the end of the file or an error occurs. We must check the error
1443 :     # first in case the file handle failed to open.
1444 :     while (! $error && ! eof $ih) {
1445 :     # Get the current line.
1446 :     my @row = Tracer::GetLine($ih);
1447 :     # Get the correspondence direction and check for a reverse arrow.
1448 :     $reverseFound = 1 if ($row[8] eq '<-');
1449 :     # If we're in converse mode, reformat the line.
1450 :     if ($converse) {
1451 : parrello 1.39 ReverseGeneCorrespondenceRow(\@row);
1452 : parrello 1.37 }
1453 :     # Validate the row.
1454 :     if (ValidateGeneCorrespondenceRow(\@row)) {
1455 : parrello 1.44 Trace("Invalid row $. found in correspondence file $fileName.") if T(Corr => 1);
1456 : parrello 1.37 $error = 1;
1457 :     }
1458 :     # If this row is in the correct direction, keep it.
1459 : parrello 1.40 if ($all || $row[8] ne '<-') {
1460 : parrello 1.37 push @corrList, \@row;
1461 :     }
1462 :     }
1463 :     # Close the input file.
1464 :     close $ih;
1465 : parrello 1.57 # If we have no errors, keep the result.
1466 : parrello 1.37 if (! $error) {
1467 : parrello 1.57 $retVal = \@corrList;
1468 : parrello 1.37 }
1469 :     # Return the result (if any).
1470 :     return $retVal;
1471 :     }
1472 :    
1473 : parrello 1.39 =head3 ReverseGeneCorrespondenceRow
1474 :    
1475 :     ServerThing::ReverseGeneCorrespondenceRow($row)
1476 :    
1477 :     Convert a gene correspondence row to represent the converse correspondence. The
1478 :     elements in the row will be reordered to represent a correspondence from the
1479 :     target genome to the source genome.
1480 :    
1481 :     =over 4
1482 :    
1483 :     =item row
1484 :    
1485 :     Reference to a list containing a single row from a L</Gene Correspondence List>.
1486 :    
1487 :     =back
1488 :    
1489 :     =cut
1490 :    
1491 :     sub ReverseGeneCorrespondenceRow {
1492 :     # Get the parameters.
1493 :     my ($row) = @_;
1494 :     # Flip the row in place.
1495 :     ($row->[1], $row->[0], $row->[2], $row->[3], $row->[5], $row->[4], $row->[7],
1496 : parrello 1.41 $row->[6], $row->[8], $row->[9], $row->[10], $row->[14],
1497 : parrello 1.39 $row->[15], $row->[16], $row->[11], $row->[12], $row->[13], $row->[17]) = @$row;
1498 : parrello 1.41 # Flip the arrow.
1499 :     $row->[8] = ARROW_FLIP->{$row->[8]};
1500 :     # Flip the pairs.
1501 : parrello 1.42 my @elements = split /,/, $row->[3];
1502 : parrello 1.45 $row->[3] = join(",", map { join(":", reverse split /:/, $_) } @elements);
1503 : parrello 1.39 }
1504 : parrello 1.37
1505 :     =head3 ValidateGeneCorrespondenceRow
1506 :    
1507 :     my $errorCount = ServerThing::ValidateGeneCorrespondenceRow($row);
1508 :    
1509 :     Validate a gene correspondence row. The numeric fields are checked to insure they
1510 :     are numeric and the source and target gene IDs are validated. The return value will
1511 :     indicate the number of errors found.
1512 :    
1513 :     =over 4
1514 :    
1515 :     =item row
1516 :    
1517 :     Reference to a list containing a single row from a L</Gene Correspondence List>.
1518 :    
1519 :     =item RETURN
1520 :    
1521 :     Returns the number of errors found in the row. A return of C<0> indicates the row
1522 :     is valid.
1523 :    
1524 :     =back
1525 :    
1526 :     =cut
1527 :    
1528 :     sub ValidateGeneCorrespondenceRow {
1529 :     # Get the parameters.
1530 :     my ($row, $genome1, $genome2) = @_;
1531 :     # Denote no errors have been found so far.
1532 :     my $retVal = 0;
1533 :     # Check for non-numeric values in the number columns.
1534 :     for my $col (@{NUM_COLS()}) {
1535 :     unless ($row->[$col] =~ /^-?\d+\.?\d*(?:e[+-]?\d+)?$/) {
1536 : parrello 1.44 Trace("Gene correspondence error. \"$row->[$col]\" not numeric.") if T(Corr => 2);
1537 : parrello 1.37 $retVal++;
1538 :     }
1539 :     }
1540 :     # Check the gene IDs.
1541 :     for my $col (0, 1) {
1542 :     unless ($row->[$col] =~ /^fig\|\d+\.\d+\.\w+\.\d+$/) {
1543 : parrello 1.44 Trace("Gene correspondence error. \"$row->[$col]\" not a gene ID.") if T(Corr => 2);
1544 : parrello 1.37 $retVal++;
1545 : parrello 1.36 }
1546 :     }
1547 : parrello 1.37 # Verify the arrow.
1548 :     unless (exists ARROW_FLIP->{$row->[8]}) {
1549 : parrello 1.44 Trace("Gene correspondence error. \"$row->[8]\" not an arrow.") if T(Corr => 2);
1550 : parrello 1.37 $retVal++;
1551 :     }
1552 :     # Return the error count.
1553 : parrello 1.36 return $retVal;
1554 :     }
1555 :    
1556 : parrello 1.53 =head3 GetCorrespondenceData
1557 :    
1558 :     my $corrList = ServerThing::GetCorrespondenceData($genome1, $genome2, $passive, $full);
1559 :    
1560 :     Return the L</Gene Correspondence List> for the specified source and target genomes. If the
1561 :     list is in a file, it will be read. If the file does not exist, it may be created.
1562 :    
1563 :     =over 4
1564 :    
1565 :     =item genome1
1566 :    
1567 :     ID of the source genome.
1568 :    
1569 :     =item genome2
1570 :    
1571 :     ID of the target genome.
1572 :    
1573 :     =item passive
1574 :    
1575 :     If TRUE, then the correspondence file will not be created if it does not exist.
1576 :    
1577 :     =item full
1578 :    
1579 :     If TRUE, then both directions of the correspondence will be represented; otherwise, only
1580 :     correspondences from the source to the target (including bidirectional corresopndences)
1581 :     will be included.
1582 :    
1583 :     =item RETURN
1584 :    
1585 :     Returns a L</Gene Correspondence List> in the form of a reference to a list of lists, or an
1586 :     undefined value if an error occurs or no file exists and passive mode was specified.
1587 :    
1588 :     =back
1589 :    
1590 :     =cut
1591 :    
1592 :     sub GetCorrespondenceData {
1593 :     # Get the parameters.
1594 :     my ($genome1, $genome2, $passive, $full) = @_;
1595 :     # Declare the return variable.
1596 :     my $retVal;
1597 :     # Check for a gene correspondence file.
1598 :     my ($fileName, $converse) = ServerThing::CheckForGeneCorrespondenceFile($genome1, $genome2);
1599 :     if ($fileName) {
1600 :     # Here we found one, so read it in.
1601 :     $retVal = ServerThing::ReadGeneCorrespondenceFile($fileName, $converse, $full);
1602 :     }
1603 :     # Were we successful?
1604 :     if (! defined $retVal) {
1605 :     # Here we either don't have a correspondence file, or the one that's there is
1606 :     # invalid. If we are NOT in passive mode, then this means we need to create
1607 :     # the file.
1608 :     if (! $passive) {
1609 :     ($fileName, $converse) = ServerThing::CreateGeneCorrespondenceFile($genome1, $genome2);
1610 :     # Now try reading the new file.
1611 :     if (defined $fileName) {
1612 :     $retVal = ServerThing::ReadGeneCorrespondenceFile($fileName, $converse);
1613 :     }
1614 :     }
1615 :     }
1616 :     # Return the result.
1617 :     return $retVal;
1618 : parrello 1.85
1619 : parrello 1.53 }
1620 :    
1621 : parrello 1.9
1622 :     =head2 Internal Utility Methods
1623 :    
1624 :     The methods in this section are used internally by this package.
1625 :    
1626 : parrello 1.6 =head3 RunRequest
1627 :    
1628 : parrello 1.62 ServerThing::RunRequest($cgi, $serverThing, $docURL);
1629 : parrello 1.6
1630 :     Run a request from the specified server using the incoming CGI parameter
1631 :     object for the parameters.
1632 :    
1633 :     =over 4
1634 :    
1635 :     =item cgi
1636 :    
1637 : parrello 1.49 CGI query object containing the parameters from the web service request. The
1638 :     significant parameters are as follows.
1639 :    
1640 :     =over 8
1641 :    
1642 :     =item function
1643 :    
1644 :     Name of the function to run.
1645 :    
1646 :     =item args
1647 :    
1648 :     Parameters for the function.
1649 :    
1650 :     =item encoding
1651 :    
1652 :     Encoding scheme for the function parameters, either C<yaml> (the default) or C<json> (used
1653 :     by the Java interface).
1654 :    
1655 :     =back
1656 :    
1657 :     Certain unusual requests can come in outside of the standard function interface.
1658 :     These are indicated by special parameters that override all the others.
1659 :    
1660 :     =over 8
1661 :    
1662 :     =item pod
1663 :    
1664 :     Display a POD documentation module.
1665 :    
1666 :     =item code
1667 :    
1668 :     Display an example code file.
1669 :    
1670 :     =item file
1671 :    
1672 :     Transfer a file (not implemented).
1673 :    
1674 :     =back
1675 : parrello 1.6
1676 : parrello 1.13 =item serverThing
1677 : parrello 1.6
1678 : parrello 1.13 Server object against which to run the request.
1679 : parrello 1.6
1680 : parrello 1.62 =item docURL
1681 :    
1682 :     URL to use for POD documentation requests.
1683 :    
1684 : parrello 1.6 =back
1685 :    
1686 :     =cut
1687 :    
1688 :     sub RunRequest {
1689 :     # Get the parameters.
1690 : parrello 1.13 my ($cgi, $serverThing, $docURL) = @_;
1691 : parrello 1.62 # Make the CGI object available to the server.
1692 :     $serverThing->{cgi} = $cgi;
1693 : parrello 1.9 # Determine the request type.
1694 : parrello 1.52 my $module = $cgi->param('pod');
1695 :     if ($module) {
1696 :     # Here we have a documentation request.
1697 :     if ($module eq 'ServerScripts') {
1698 :     # Here we list the server scripts.
1699 :     require ListServerScripts;
1700 :     ListServerScripts::main();
1701 :     } else {
1702 :     # In this case, we produce POD HTML.
1703 :     ProducePod($cgi->param('pod'));
1704 :     }
1705 : disz 1.31 } elsif ($cgi->param('code')) {
1706 : parrello 1.32 # Here the user wants to see the code for one of our scripts.
1707 :     LineNumberize($cgi->param('code'));
1708 : parrello 1.9 } elsif ($cgi->param('file')) {
1709 :     # Here we have a file request. Process according to the type.
1710 :     my $type = $cgi->param('file');
1711 :     if ($type eq 'open') {
1712 :     OpenFile($cgi->param('name'));
1713 :     } elsif ($type eq 'create') {
1714 :     CreateFile();
1715 :     } elsif ($type eq 'read') {
1716 :     ReadChunk($cgi->param('name'), $cgi->param('location'), $cgi->param('size'));
1717 :     } elsif ($type eq 'write') {
1718 :     WriteChunk($cgi->param('name'), $cgi->param('data'));
1719 :     } else {
1720 :     Die("Invalid file function \"$type\".");
1721 : parrello 1.4 }
1722 : parrello 1.1 } else {
1723 : parrello 1.9 # The default is a function request. Get the function name.
1724 : parrello 1.4 my $function = $cgi->param('function') || "";
1725 : parrello 1.15 Trace("Server function for task $$ is $function.") if T(3);
1726 : parrello 1.4 # Insure the function name is valid.
1727 : devoid 1.75 if ($function ne "methods" && exists $serverThing->{methods} && ! $serverThing->{methods}{$function}) {
1728 :     SendError("Invalid function name.", "$function not found.")
1729 :     } else {
1730 :     # Determing the encoding scheme. The default is YAML.
1731 :     my $encoding = $cgi->param('encoding') || 'yaml';
1732 :     # Optional callback for json encoded documents
1733 :     my $callback = $cgi->param('callback');
1734 :     # The parameter structure will go in here.
1735 :     my $args = {};
1736 :     # Start the timer.
1737 :     my $start = time();
1738 :     # The output document goes in here.
1739 :     my $document;
1740 :     # Protect from errors.
1741 :     eval {
1742 :     # Here we parse the arguments. This is affected by the encoding parameter.
1743 :     # Get the argument string.
1744 :     my $argString = $cgi->param('args');
1745 :     # Only proceed if we found one.
1746 :     if ($argString) {
1747 :     if ($encoding eq 'yaml') {
1748 :     # Parse the arguments using YAML.
1749 :     $args = YAML::Load($argString);
1750 : parrello 1.85 } elsif ($encoding eq 'yaml2') {
1751 :     # Parse the arguments using C-based YAML.
1752 :     $args = YAML::XS::Load($argString);
1753 : devoid 1.75 } elsif ($encoding eq 'json') {
1754 :     # Parse the arguments using JSON.
1755 :     Trace("Incoming string is:\n$argString") if T(3);
1756 :     $args = JSON::Any->jsonToObj($argString);
1757 :     } else {
1758 :     Die("Invalid encoding type $encoding.");
1759 :     }
1760 : devoid 1.74 }
1761 : devoid 1.75 };
1762 :     # Check to make sure we got everything.
1763 : parrello 1.1 if ($@) {
1764 : devoid 1.75 SendError($@, "Error formatting parameters.");
1765 :     } elsif (! $function) {
1766 :     SendError("No function specified.", "No function specified.");
1767 : parrello 1.1 } else {
1768 : devoid 1.75 # Insure we're connected to the correct database.
1769 :     my $dbName = $cgi->param('dbName');
1770 :     if ($dbName && exists $serverThing->{db}) {
1771 :     ChangeDB($serverThing, $dbName);
1772 :     }
1773 :     # Run the request.
1774 : olson 1.79 if ($serverThing->{raw_methods}->{$function})
1775 :     {
1776 :     $document = eval { $serverThing->$function($cgi) };
1777 :     }
1778 :     else
1779 :     {
1780 :     $document = eval { $serverThing->$function($args) };
1781 :     }
1782 : devoid 1.75 # If we have an error, create an error document.
1783 :     if ($@) {
1784 :     SendError($@, "Error detected by service.");
1785 :     Trace("Error encountered by service: $@") if T(0);
1786 : devoid 1.74 } else {
1787 : devoid 1.75 # No error, so we output the result. Start with an HTML header.
1788 :     if ($encoding eq 'yaml') {
1789 :     print $cgi->header(-type => 'text/plain');
1790 :     } else {
1791 :     print $cgi->header(-type => 'text/javascript');
1792 :     }
1793 :     # The nature of the output depends on the encoding type.
1794 :     eval {
1795 :     my $string;
1796 :     if ($encoding eq 'yaml') {
1797 :     $string = YAML::Dump($document);
1798 : parrello 1.85 } elsif ($encoding eq 'yaml2') {
1799 :     $string = YAML::XS::Dump($document);
1800 :     } elsif (defined($callback)) {
1801 : devoid 1.75 $string = $callback . "(".JSON::Any->objToJson($document).")";
1802 :     } else {
1803 :     $string = JSON::Any->objToJson($document);
1804 : parrello 1.85 }
1805 : devoid 1.75 print $string;
1806 :     MemTrace(length($string) . " bytes returned from $function by task $$.") if T(Memory => 3);
1807 :     };
1808 :     if ($@) {
1809 :     SendError($@, "Error encoding result.");
1810 :     Trace("Error encoding result: $@") if T(0);
1811 :     }
1812 : parrello 1.63 }
1813 : parrello 1.1 }
1814 : devoid 1.75 # Stop the timer.
1815 :     my $duration = int(time() - $start + 0.5);
1816 :     Trace("Function $function executed in $duration seconds by task $$.") if T(2);
1817 : parrello 1.1 }
1818 :     }
1819 :     }
1820 :    
1821 : parrello 1.9 =head3 CreateFile
1822 :    
1823 :     ServerThing::CreateFile();
1824 :    
1825 :     Create a new, empty temporary file and send its name back to the client.
1826 :    
1827 :     =cut
1828 :    
1829 :     sub CreateFile {
1830 :     ##TODO: Code
1831 :     }
1832 :    
1833 :     =head3 OpenFile
1834 : parrello 1.6
1835 : parrello 1.9 ServerThing::OpenFile($name);
1836 : parrello 1.1
1837 : parrello 1.9 Send the length of the named file back to the client.
1838 :    
1839 :     =over 4
1840 :    
1841 :     =item name
1842 :    
1843 :     ##TODO: name description
1844 :    
1845 :     =back
1846 :    
1847 :     =cut
1848 :    
1849 :     sub OpenFile {
1850 :     # Get the parameters.
1851 :     my ($name) = @_;
1852 :     ##TODO: Code
1853 :     }
1854 : parrello 1.1
1855 : parrello 1.9 =head3 ReadChunk
1856 : parrello 1.1
1857 : parrello 1.9 ServerThing::ReadChunk($name, $location, $size);
1858 : parrello 1.1
1859 : parrello 1.9 Read the indicated number of bytes from the specified location of the
1860 :     named file and send them back to the client.
1861 : parrello 1.1
1862 :     =over 4
1863 :    
1864 :     =item name
1865 :    
1866 : parrello 1.9 ##TODO: name description
1867 : parrello 1.1
1868 : parrello 1.9 =item location
1869 : parrello 1.1
1870 : parrello 1.9 ##TODO: location description
1871 : parrello 1.1
1872 : parrello 1.9 =item size
1873 : parrello 1.1
1874 : parrello 1.9 ##TODO: size description
1875 : parrello 1.1
1876 :     =back
1877 :    
1878 :     =cut
1879 :    
1880 : parrello 1.9 sub ReadChunk {
1881 : parrello 1.1 # Get the parameters.
1882 : parrello 1.9 my ($name, $location, $size) = @_;
1883 :     ##TODO: Code
1884 : parrello 1.1 }
1885 :    
1886 : parrello 1.9 =head3 WriteChunk
1887 : parrello 1.1
1888 : parrello 1.9 ServerThing::WriteChunk($name, $data);
1889 : parrello 1.8
1890 : parrello 1.9 Write the specified data to the named file.
1891 : parrello 1.8
1892 :     =over 4
1893 :    
1894 :     =item name
1895 :    
1896 : parrello 1.9 ##TODO: name description
1897 :    
1898 :     =item data
1899 :    
1900 :     ##TODO: data description
1901 :    
1902 :     =back
1903 :    
1904 :     =cut
1905 :    
1906 :     sub WriteChunk {
1907 :     # Get the parameters.
1908 :     my ($name, $data) = @_;
1909 :     ##TODO: Code
1910 :     }
1911 :    
1912 :    
1913 : disz 1.31 =head3 LineNumberize
1914 :    
1915 :     ServerThing::LineNumberize($module);
1916 :    
1917 :     Output the module line by line with line numbers
1918 :    
1919 :     =over 4
1920 :    
1921 :     =item module
1922 :    
1923 :     Name of the module to line numberized
1924 :    
1925 :     =back
1926 :    
1927 :     =cut
1928 :    
1929 :     sub LineNumberize {
1930 :     # Get the parameters.
1931 :     my ($module) = @_;
1932 :     my $fks_path = "$FIG_Config::fig_disk/dist/releases/current/FigKernelScripts/$module";
1933 :     # Start the output page.
1934 :     print CGI::header();
1935 :     print CGI::start_html(-title => 'Documentation Page',
1936 :     -style => { src => "http://servers.nmpdr.org/sapling/Html/css/ERDB.css" });
1937 :     # Protect from errors.
1938 :     eval {
1939 : parrello 1.32 if (-e $fks_path) {
1940 :     print "<pre>\n";
1941 :     my $i = 1;
1942 :     foreach my $line (`cat $fks_path`) {
1943 :     print "$i.\t$line";
1944 :     $i++;
1945 :     }
1946 :     print "</pre>\n";
1947 :     } else {
1948 :     print "File $fks_path not found";
1949 :     }
1950 : disz 1.31 };
1951 :     # Process any error.
1952 :     if ($@) {
1953 :     print CGI::blockquote({ class => 'error' }, $@);
1954 :     }
1955 :     # Close off the page.
1956 :     print CGI::end_html();
1957 :    
1958 :     }
1959 :    
1960 : parrello 1.9 =head3 ProducePod
1961 :    
1962 :     ServerThing::ProducePod($module);
1963 :    
1964 :     Output the POD documentation for the specified module.
1965 :    
1966 :     =over 4
1967 : parrello 1.8
1968 : parrello 1.9 =item module
1969 : parrello 1.8
1970 : parrello 1.9 Name of the module whose POD document is to be displayed.
1971 : parrello 1.8
1972 :     =back
1973 :    
1974 :     =cut
1975 :    
1976 : parrello 1.9 sub ProducePod {
1977 : parrello 1.8 # Get the parameters.
1978 : parrello 1.9 my ($module) = @_;
1979 :     # Start the output page.
1980 :     print CGI::header();
1981 : parrello 1.46 print CGI::start_html(-title => "$module Documentation Page",
1982 : parrello 1.9 -style => { src => "http://servers.nmpdr.org/sapling/Html/css/ERDB.css" });
1983 :     # Protect from errors.
1984 :     eval {
1985 :     # We'll format the HTML text in here.
1986 :     require DocUtils;
1987 : devoid 1.75 my $html = DocUtils::ShowPod($module, "http://pubseed.theseed.org/sapling/server.cgi?pod=");
1988 : parrello 1.9 # Output the POD HTML.
1989 :     print $html;
1990 :     };
1991 :     # Process any error.
1992 :     if ($@) {
1993 :     print CGI::blockquote({ class => 'error' }, $@);
1994 : parrello 1.8 }
1995 : parrello 1.9 # Close off the page.
1996 :     print CGI::end_html();
1997 :    
1998 : parrello 1.8 }
1999 :    
2000 :     =head3 TraceErrorLog
2001 :    
2002 :     ServerThing::TraceErrorLog($name, $errorLog);
2003 :    
2004 :     Trace the specified error log file. This is a very dinky routine that
2005 :     performs a task required by L</RunTool> in multiple places.
2006 :    
2007 :     =over 4
2008 :    
2009 :     =item name
2010 :    
2011 :     Name of the tool relevant to the log file.
2012 :    
2013 :     =item errorLog
2014 :    
2015 :     Name of the log file.
2016 :    
2017 :     =back
2018 :    
2019 :     =cut
2020 :    
2021 :     sub TraceErrorLog {
2022 :     my ($name, $errorLog) = @_;
2023 :     my $errorData = Tracer::GetFile($errorLog);
2024 :     Trace("$name error log:\n$errorData");
2025 :     }
2026 :    
2027 : parrello 1.10 =head3 SendError
2028 :    
2029 :     ServerThing::SendError($message, $status);
2030 :    
2031 :     Fail an HTTP request with the specified error message and the specified
2032 :     status message.
2033 :    
2034 :     =over 4
2035 :    
2036 :     =item message
2037 :    
2038 :     Detailed error message. This is sent as the page content.
2039 :    
2040 :     =item status
2041 :    
2042 :     Status message. This is sent as part of the status code.
2043 :    
2044 :     =back
2045 :    
2046 :     =cut
2047 :    
2048 :     sub SendError {
2049 :     # Get the parameters.
2050 :     my ($message, $status) = @_;
2051 : parrello 1.78 warn ("SAS Error \"$status\" $message\n");
2052 : parrello 1.30 # Check for a DBserver error. These can be retried and get a special status
2053 :     # code.
2054 :     my $realStatus;
2055 :     if ($message =~ /DBServer Error:\s+/) {
2056 :     $realStatus = "503 $status";
2057 :     } else {
2058 : olson 1.79 $realStatus = "500 $status";
2059 : parrello 1.30 }
2060 : parrello 1.10 # Print the header and the status message.
2061 :     print CGI::header(-type => 'text/plain',
2062 : parrello 1.30 -status => $realStatus);
2063 : parrello 1.10 # Print the detailed message.
2064 :     print $message;
2065 :     }
2066 :    
2067 :    
2068 : devoid 1.75 =head3 Log
2069 :    
2070 :     Log($msg);
2071 :    
2072 :     Write a message to the log. This is a temporary hack until we can figure out how to get
2073 :     normal tracing and error logging working.
2074 :    
2075 :     =over 4
2076 :    
2077 :     =item msg
2078 :    
2079 :     Message to write. It will be appended to the C<servers.log> file in the FIG temporary directory.
2080 :    
2081 :     =back
2082 :    
2083 :     =cut
2084 :    
2085 :     sub Log {
2086 :     # Get the parameters.
2087 :     my ($msg) = @_;
2088 :     # Open the log file for appending.
2089 :     open(my $oh, ">>$FIG_Config::temp/servers.log") || Confess("Log error: $!");
2090 :     print $oh "$msg\n";
2091 :     close $oh;
2092 :     }
2093 :    
2094 : olson 1.79 package ServerReturn;
2095 :    
2096 :     =head1 ServerReturn
2097 :    
2098 :     ServerReturn is a little class used to encapsulate responses to be
2099 :     sent back toclients. It holds an code code (to be pushed into
2100 :     a HTTP response response), a short message, and long details.
2101 :    
2102 :     =cut
2103 :    
2104 :     use strict;
2105 :     use base 'Class::Accessor';
2106 :    
2107 :     __PACKAGE__->mk_accessors(qw(code msg body));
2108 :    
2109 :     sub new
2110 :     {
2111 :     my($class, $code, $msg, $body) = @_;
2112 :     my $self = {
2113 :     code => $code,
2114 :     msg => $msg,
2115 :     body => $body,
2116 :     };
2117 :     return bless $self, $class;
2118 :     }
2119 :    
2120 :     sub package_response
2121 :     {
2122 :     my($self) = @_;
2123 :     return pack("nN/aN/a", @{$self}{qw(code msg body)});
2124 :     }
2125 :    
2126 : disz 1.31 1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3