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

Annotation of /FigKernelPackages/ServerThing.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3