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

Annotation of /FigKernelPackages/ServerThing.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3