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

Annotation of /FigKernelPackages/ServerThing.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

1 : parrello 1.1 #!/usr/bin/perl -w
2 :    
3 :     package ServerThing;
4 :    
5 :     use strict;
6 :     use Tracer;
7 :     use YAML;
8 :     use ERDB;
9 :     use TestUtils;
10 :     use Time::HiRes;
11 : parrello 1.9 use File::Temp;
12 : parrello 1.10 use ErrorMessage;
13 : parrello 1.1 use CGI;
14 : parrello 1.9 no warnings qw(once);
15 : parrello 1.1
16 : parrello 1.11 # Maximum number of requests to run per invocation.
17 : parrello 1.29 use constant MAX_REQUESTS => 5000;
18 : parrello 1.11
19 : parrello 1.1 =head1 General Server Helper
20 :    
21 :     This package provides a method-- I<RunServer>-- that can be called from a CGI
22 : parrello 1.9 script to perform the duties of a FIG server. RunServer is called with two
23 :     parameters: the name of the server package (e.g. C<SAP> for B<SAP.pm>) and
24 :     the first command-line parameter. The command-line parameter (if defined) will
25 :     be used as the tracing key, and also indicates that the script is being invoked
26 :     from the command line rather than over the web.
27 : parrello 1.1
28 :     =cut
29 :    
30 :     sub RunServer {
31 :     # Get the parameters.
32 : parrello 1.9 my ($serverName, $key) = @_;
33 : parrello 1.25 # Set up tracing. We never do CGI tracing here; the only question is whether
34 :     # or not the caller passed in a tracing key. If he didn't, we use the server
35 :     # name.
36 : parrello 1.32 ETracing($key || $serverName, destType => 'APPEND', level => '0 ServerThing');
37 : parrello 1.9 # Turn off YAML compression, which causes problems with some of our hash keys.
38 :     $YAML::CompressSeries = 0;
39 : parrello 1.13 # Create the server object.
40 : parrello 1.15 Trace("Requiring $serverName for task $$.") if T(3);
41 : parrello 1.13 eval {
42 :     require "$serverName.pm";
43 :     };
44 :     # If we have an error, create an error document.
45 :     if ($@) {
46 :     SendError($@, "Could not load server module.");
47 :     } else {
48 :     # Having successfully loaded the server code, we create the object.
49 :     my $serverThing = eval("$serverName" . '->new()');
50 : parrello 1.15 Trace("$serverName object created for task $$.") if T(2);
51 : parrello 1.13 # If we have an error, create an error document.
52 :     if ($@) {
53 :     SendError($@, "Could not start server.");
54 : parrello 1.3 } else {
55 : parrello 1.13 # No error, so now we can process the request.
56 :     my $cgi;
57 :     if (! defined $key) {
58 :     # No tracing key, so presume we're a web service. Check for Fast CGI.
59 :     if ($ENV{REQUEST_METHOD} eq '') {
60 :     # Count the number of requests.
61 :     my $requests = 0;
62 : parrello 1.24 Trace("Starting Fast CGI loop.") if T(3);
63 : parrello 1.13 # Loop through the fast CGI requests. If we have request throttling,
64 :     # we exit after a maximum number of requests has been exceeded.
65 :     require CGI::Fast;
66 : parrello 1.23 while ((MAX_REQUESTS == 0 || ++$requests < MAX_REQUESTS) &&
67 :     ($cgi = new CGI::Fast())) {
68 : parrello 1.13 RunRequest($cgi, $serverThing);
69 : parrello 1.16 Trace("Request $requests complete in task $$.") if T(3);
70 : parrello 1.13 }
71 : parrello 1.15 Trace("Terminating FastCGI task $$ after $requests requests.") if T(2);
72 : parrello 1.13 } else {
73 :     # Here we have a normal web service (non-Fast).
74 :     my $cgi = CGI->new();
75 :     # Check for a source parameter. This gets used as the tracing key.
76 :     $key = $cgi->param('source');
77 :     # Run this request.
78 :     RunRequest($cgi, $serverThing);
79 :     }
80 : parrello 1.6 } else {
81 : parrello 1.13 # We're being invoked from the command line. Use the tracing
82 :     # key to find the parm file and create the CGI object from that.
83 :     my $ih = Open(undef, "<$FIG_Config::temp/$key.parms");
84 :     $cgi = CGI->new($ih);
85 :     # Run this request.
86 :     RunRequest($cgi, $serverThing);
87 : parrello 1.6 }
88 : parrello 1.3 }
89 : parrello 1.1 }
90 : parrello 1.6 }
91 :    
92 :    
93 : parrello 1.9 =head2 Server Utility Methods
94 :    
95 :     The methods in this section are utilities of general use to the various
96 :     server modules.
97 :    
98 : parrello 1.21 =head3 AddSubsystemFilter
99 :    
100 :     ServerThing::AddSubsystemFilter(\$filter, $args);
101 :    
102 :     Add subsystem filtering information to the specified query filter clause
103 :     based on data in the argument hash. The argument hash will be checked for
104 : parrello 1.22 the C<-usable> parameter, which includes or excludes unusuable subsystems, and
105 :     the C<-exclude> parameter, which lists types of subsystems that should be
106 : parrello 1.21 excluded.
107 :    
108 :     =over 4
109 :    
110 :     =item filter
111 :    
112 :     Reference to the current filter string. If additional filtering is required,
113 :     this string will be updated.
114 :    
115 :     =item args
116 :    
117 :     Reference to the parameter hash for the current server call. This hash will
118 : parrello 1.22 be examined for the C<-usable> and C<-exclude> parameters.
119 : parrello 1.21
120 :     =back
121 :    
122 :     =cut
123 :    
124 :     use constant SS_TYPE_EXCLUDE_ITEMS => { 'cluster-based' => 1,
125 :     experimental => 1,
126 :     private => 1 };
127 :    
128 :     sub AddSubsystemFilter {
129 :     # Get the parameters.
130 :     my ($filter, $args) = @_;
131 :     # We'll put the new filter stuff in here.
132 :     my @newFilters;
133 :     # Unless unusable subsystems are desired, we must add a clause to the filter.
134 : parrello 1.22 # The default is that only usable subsystems are included.
135 :     my $usable = 1;
136 :     # This default can be overridden by the "-usable" parameter.
137 :     if (exists $args->{-usable}) {
138 :     $usable = $args->{-usable};
139 :     }
140 :     # If we're restricting to usable subsystems, add a filter to that effect.
141 :     if ($usable) {
142 : parrello 1.21 push @newFilters, "Subsystem(usable) = 1";
143 :     }
144 :     # Check for exclusion filters.
145 :     my $exclusions = ServerThing::GetIdList(-exclude => $args, 1);
146 :     for my $exclusion (@$exclusions) {
147 :     if (! SS_TYPE_EXCLUDE_ITEMS->{$exclusion}) {
148 :     Confess("Invalid exclusion type \"$exclusion\".");
149 :     } else {
150 :     # Here we have to exclude subsystems of the specified type.
151 :     push @newFilters, "Subsystem($exclusion) = 0";
152 :     }
153 :     }
154 :     # Do we need to update the incoming filter?
155 :     if (@newFilters) {
156 :     # Yes. If the incoming filter is nonempty, push it onto the list
157 :     # so it gets included in the result.
158 :     if ($$filter) {
159 :     push @newFilters, $$filter;
160 :     }
161 :     # Put all the filters together to form the new filter.
162 :     $$filter = join(" AND ", @newFilters);
163 : parrello 1.26 Trace("Subsystem filter is $$filter.") if T(ServerUtilities => 3);
164 : parrello 1.21 }
165 :     }
166 :    
167 :    
168 :    
169 : parrello 1.9 =head3 GetIdList
170 :    
171 : parrello 1.19 my $ids = ServerThing::GetIdList($name => $args, $optional);
172 : parrello 1.9
173 :     Get a named list of IDs from an argument structure. If the IDs are
174 :     missing, or are not a list, an error will occur.
175 :    
176 :     =over 4
177 :    
178 :     =item name
179 :    
180 :     Name of the argument structure member that should contain the ID list.
181 :    
182 :     =item args
183 :    
184 :     Argument structure from which the ID list is to be extracted.
185 :    
186 : parrello 1.19 =item optional (optional)
187 :    
188 :     If TRUE, then a missing value will not generate an error. Instead, an empty list
189 :     will be returned. The default is FALSE.
190 :    
191 : parrello 1.9 =item RETURN
192 :    
193 :     Returns a reference to a list of IDs taken from the argument structure.
194 :    
195 :     =back
196 :    
197 :     =cut
198 :    
199 :     sub GetIdList {
200 :     # Get the parameters.
201 : parrello 1.19 my ($name, $args, $optional) = @_;
202 : parrello 1.32 # Check the argument format.
203 :     if (ref $args ne 'HASH') {
204 :     Confess("No '$name' parameter present.");
205 :     }
206 : parrello 1.9 # Try to get the IDs from the argument structure.
207 :     my $retVal = $args->{$name};
208 : parrello 1.19 # Was a member found?
209 :     if (! defined $retVal) {
210 :     # No. If we're optional, return an empty list; otherwise throw an error.
211 :     if ($optional) {
212 :     $retVal = [];
213 :     } else {
214 :     Confess("No '$name' parameter found.");
215 :     }
216 :     } else {
217 :     # Here we found something. Get the parameter type. We was a list reference.
218 :     # If it's a scalar, we'll convert it to a singleton list. If it's anything
219 :     # else, it's an error.
220 :     my $type = ref $retVal;
221 :     if (! $type) {
222 :     $retVal = [$retVal];
223 :     } elsif ($type ne 'ARRAY') {
224 :     Confess("The '$name' parameter must be a list.");
225 :     }
226 : parrello 1.9 }
227 :     # Return the result.
228 :     return $retVal;
229 :     }
230 :    
231 :    
232 :     =head3 RunTool
233 :    
234 :     ServerThing::RunTool($name => $cmd);
235 :    
236 :     Run a command-line tool. A non-zero return value from the tool will cause
237 :     a fatal error, and the tool's error log will be traced.
238 :    
239 :     =over 4
240 :    
241 :     =item name
242 :    
243 :     Name to give to the tool in the error output.
244 :    
245 :     =item cmd
246 :    
247 :     Command to use for running the tool. This should be the complete command line.
248 :     The command should not contain any fancy piping, though it may redirect the
249 :     standard input and output. The command will be modified by this method to
250 :     redirect the error output to a temporary file.
251 :    
252 :     =back
253 :    
254 :     =cut
255 :    
256 :     sub RunTool {
257 :     # Get the parameters.
258 :     my ($name, $cmd) = @_;
259 :     # Compute the log file name.
260 :     my $errorLog = "$FIG_Config::temp/errors$$.log";
261 :     # Execute the command.
262 : parrello 1.26 Trace("Executing command: $cmd") if T(ServerUtilities => 3);
263 : parrello 1.9 my $res = system("$cmd 2> $errorLog");
264 : parrello 1.26 Trace("Return from $name tool is $res.") if T(ServerUtilities => 3);
265 : parrello 1.9 # Check the result code.
266 :     if ($res != 0) {
267 :     # We have an error. If tracing is on, trace it.
268 : parrello 1.26 if (T(ServerUtilities => 1)) {
269 : parrello 1.9 TraceErrorLog($name, $errorLog);
270 :     }
271 :     # Delete the error log.
272 :     unlink $errorLog;
273 :     # Confess the error.
274 : parrello 1.10 Confess("$name command failed with error code $res.");
275 : parrello 1.9 } else {
276 :     # Everything worked. Trace the error log if necessary.
277 : parrello 1.26 if (T(ServerUtilities => 3) && -s $errorLog) {
278 : parrello 1.9 TraceErrorLog($name, $errorLog);
279 :     }
280 :     # Delete the error log if there is one.
281 :     unlink $errorLog;
282 :     }
283 :     }
284 :    
285 :    
286 :     =head2 Internal Utility Methods
287 :    
288 :     The methods in this section are used internally by this package.
289 :    
290 : parrello 1.6 =head3 RunRequest
291 :    
292 : parrello 1.9 ServerThing::RunRequest($cgi, $serverName);
293 : parrello 1.6
294 :     Run a request from the specified server using the incoming CGI parameter
295 :     object for the parameters.
296 :    
297 :     =over 4
298 :    
299 :     =item cgi
300 :    
301 :     CGI query object containing the parameters from the web service request.
302 :    
303 : parrello 1.13 =item serverThing
304 : parrello 1.6
305 : parrello 1.13 Server object against which to run the request.
306 : parrello 1.6
307 :     =back
308 :    
309 :     =cut
310 :    
311 :     sub RunRequest {
312 :     # Get the parameters.
313 : parrello 1.13 my ($cgi, $serverThing, $docURL) = @_;
314 : parrello 1.9 # Determine the request type.
315 :     if ($cgi->param('pod')) {
316 : parrello 1.4 # Here we have a documentation request. In this case, we produce POD HTML.
317 : parrello 1.9 ProducePod($cgi->param('pod'));
318 : disz 1.31 } elsif ($cgi->param('code')) {
319 : parrello 1.32 # Here the user wants to see the code for one of our scripts.
320 :     LineNumberize($cgi->param('code'));
321 : parrello 1.9 } elsif ($cgi->param('file')) {
322 :     # Here we have a file request. Process according to the type.
323 :     my $type = $cgi->param('file');
324 :     if ($type eq 'open') {
325 :     OpenFile($cgi->param('name'));
326 :     } elsif ($type eq 'create') {
327 :     CreateFile();
328 :     } elsif ($type eq 'read') {
329 :     ReadChunk($cgi->param('name'), $cgi->param('location'), $cgi->param('size'));
330 :     } elsif ($type eq 'write') {
331 :     WriteChunk($cgi->param('name'), $cgi->param('data'));
332 :     } else {
333 :     Die("Invalid file function \"$type\".");
334 : parrello 1.4 }
335 : parrello 1.1 } else {
336 : parrello 1.9 # The default is a function request. Get the function name.
337 : parrello 1.4 my $function = $cgi->param('function') || "";
338 : parrello 1.15 Trace("Server function for task $$ is $function.") if T(3);
339 : parrello 1.4 # Insure the function name is valid.
340 :     Die("Invalid function name.")
341 :     if $function =~ /\W/;
342 :     # The parameter structure will go in here.
343 :     my $args;
344 :     # Start the timer.
345 :     my $start = time();
346 :     # The output document goes in here.
347 :     my $document;
348 :     # The sapling database goes in here.
349 :     my $sapling;
350 :     # Protect from errors.
351 : parrello 1.1 eval {
352 : parrello 1.4 # Parse the arguments.
353 :     $args = YAML::Load($cgi->param('args'));
354 : parrello 1.1 };
355 : parrello 1.4 # Check to make sure we got everything.
356 : parrello 1.1 if ($@) {
357 : parrello 1.10 SendError($@, "Error formatting parameters.");
358 : parrello 1.4 } elsif (! $function) {
359 : parrello 1.10 SendError("No function specified.", "No function specified.");
360 : parrello 1.1 } else {
361 : parrello 1.30 $document = eval { $serverThing->$function($args) };
362 : parrello 1.1 # If we have an error, create an error document.
363 :     if ($@) {
364 : parrello 1.13 SendError($@, "Error detected by service.");
365 : parrello 1.32 Trace("Error encountered by service: $@") if T(0);
366 : parrello 1.1 } else {
367 : parrello 1.13 # No error, so we output the result.
368 :     print $cgi->header(-type => 'text/plain');
369 : parrello 1.18 my $string = YAML::Dump($document);
370 :     print $string;
371 :     MemTrace(length($string) . " bytes returned from $function by task $$.") if T(Memory => 3);
372 : parrello 1.1 }
373 :     }
374 : parrello 1.4 # Stop the timer.
375 :     my $duration = int(time() - $start + 0.5);
376 : parrello 1.29 Trace("Function $function executed in $duration seconds by task $$.") if T(2);
377 : parrello 1.1 }
378 :     }
379 :    
380 : parrello 1.9 =head3 CreateFile
381 :    
382 :     ServerThing::CreateFile();
383 :    
384 :     Create a new, empty temporary file and send its name back to the client.
385 :    
386 :     =cut
387 :    
388 :     sub CreateFile {
389 :     ##TODO: Code
390 :     }
391 :    
392 :     =head3 OpenFile
393 : parrello 1.6
394 : parrello 1.9 ServerThing::OpenFile($name);
395 : parrello 1.1
396 : parrello 1.9 Send the length of the named file back to the client.
397 :    
398 :     =over 4
399 :    
400 :     =item name
401 :    
402 :     ##TODO: name description
403 :    
404 :     =back
405 :    
406 :     =cut
407 :    
408 :     sub OpenFile {
409 :     # Get the parameters.
410 :     my ($name) = @_;
411 :     ##TODO: Code
412 :     }
413 : parrello 1.1
414 : parrello 1.9 =head3 ReadChunk
415 : parrello 1.1
416 : parrello 1.9 ServerThing::ReadChunk($name, $location, $size);
417 : parrello 1.1
418 : parrello 1.9 Read the indicated number of bytes from the specified location of the
419 :     named file and send them back to the client.
420 : parrello 1.1
421 :     =over 4
422 :    
423 :     =item name
424 :    
425 : parrello 1.9 ##TODO: name description
426 : parrello 1.1
427 : parrello 1.9 =item location
428 : parrello 1.1
429 : parrello 1.9 ##TODO: location description
430 : parrello 1.1
431 : parrello 1.9 =item size
432 : parrello 1.1
433 : parrello 1.9 ##TODO: size description
434 : parrello 1.1
435 :     =back
436 :    
437 :     =cut
438 :    
439 : parrello 1.9 sub ReadChunk {
440 : parrello 1.1 # Get the parameters.
441 : parrello 1.9 my ($name, $location, $size) = @_;
442 :     ##TODO: Code
443 : parrello 1.1 }
444 :    
445 : parrello 1.9 =head3 WriteChunk
446 : parrello 1.1
447 : parrello 1.9 ServerThing::WriteChunk($name, $data);
448 : parrello 1.8
449 : parrello 1.9 Write the specified data to the named file.
450 : parrello 1.8
451 :     =over 4
452 :    
453 :     =item name
454 :    
455 : parrello 1.9 ##TODO: name description
456 :    
457 :     =item data
458 :    
459 :     ##TODO: data description
460 :    
461 :     =back
462 :    
463 :     =cut
464 :    
465 :     sub WriteChunk {
466 :     # Get the parameters.
467 :     my ($name, $data) = @_;
468 :     ##TODO: Code
469 :     }
470 :    
471 :    
472 : disz 1.31 =head3 LineNumberize
473 :    
474 :     ServerThing::LineNumberize($module);
475 :    
476 :     Output the module line by line with line numbers
477 :    
478 :     =over 4
479 :    
480 :     =item module
481 :    
482 :     Name of the module to line numberized
483 :    
484 :     =back
485 :    
486 :     =cut
487 :    
488 :     sub LineNumberize {
489 :     # Get the parameters.
490 :     my ($module) = @_;
491 :     my $fks_path = "$FIG_Config::fig_disk/dist/releases/current/FigKernelScripts/$module";
492 :     # Start the output page.
493 :     print CGI::header();
494 :     print CGI::start_html(-title => 'Documentation Page',
495 :     -style => { src => "http://servers.nmpdr.org/sapling/Html/css/ERDB.css" });
496 :     # Protect from errors.
497 :     eval {
498 : parrello 1.32 if (-e $fks_path) {
499 :     print "<pre>\n";
500 :     my $i = 1;
501 :     foreach my $line (`cat $fks_path`) {
502 :     print "$i.\t$line";
503 :     $i++;
504 :     }
505 :     print "</pre>\n";
506 :     } else {
507 :     print "File $fks_path not found";
508 :     }
509 : disz 1.31 };
510 :     # Process any error.
511 :     if ($@) {
512 :     print CGI::blockquote({ class => 'error' }, $@);
513 :     }
514 :     # Close off the page.
515 :     print CGI::end_html();
516 :    
517 :     }
518 :    
519 : parrello 1.9 =head3 ProducePod
520 :    
521 :     ServerThing::ProducePod($module);
522 :    
523 :     Output the POD documentation for the specified module.
524 :    
525 :     =over 4
526 : parrello 1.8
527 : parrello 1.9 =item module
528 : parrello 1.8
529 : parrello 1.9 Name of the module whose POD document is to be displayed.
530 : parrello 1.8
531 :     =back
532 :    
533 :     =cut
534 :    
535 : parrello 1.9 sub ProducePod {
536 : parrello 1.8 # Get the parameters.
537 : parrello 1.9 my ($module) = @_;
538 :     # Start the output page.
539 :     print CGI::header();
540 :     print CGI::start_html(-title => 'Documentation Page',
541 :     -style => { src => "http://servers.nmpdr.org/sapling/Html/css/ERDB.css" });
542 :     # Protect from errors.
543 :     eval {
544 :     # We'll format the HTML text in here.
545 :     require DocUtils;
546 : parrello 1.20 my $html = DocUtils::ShowPod($module, "http://servers.nmpdr.org/sapling/server.cgi?pod=");
547 : parrello 1.9 # Output the POD HTML.
548 :     print $html;
549 :     };
550 :     # Process any error.
551 :     if ($@) {
552 :     print CGI::blockquote({ class => 'error' }, $@);
553 : parrello 1.8 }
554 : parrello 1.9 # Close off the page.
555 :     print CGI::end_html();
556 :    
557 : parrello 1.8 }
558 :    
559 :     =head3 TraceErrorLog
560 :    
561 :     ServerThing::TraceErrorLog($name, $errorLog);
562 :    
563 :     Trace the specified error log file. This is a very dinky routine that
564 :     performs a task required by L</RunTool> in multiple places.
565 :    
566 :     =over 4
567 :    
568 :     =item name
569 :    
570 :     Name of the tool relevant to the log file.
571 :    
572 :     =item errorLog
573 :    
574 :     Name of the log file.
575 :    
576 :     =back
577 :    
578 :     =cut
579 :    
580 :     sub TraceErrorLog {
581 :     my ($name, $errorLog) = @_;
582 :     my $errorData = Tracer::GetFile($errorLog);
583 :     Trace("$name error log:\n$errorData");
584 :     }
585 :    
586 : parrello 1.10 =head3 SendError
587 :    
588 :     ServerThing::SendError($message, $status);
589 :    
590 :     Fail an HTTP request with the specified error message and the specified
591 :     status message.
592 :    
593 :     =over 4
594 :    
595 :     =item message
596 :    
597 :     Detailed error message. This is sent as the page content.
598 :    
599 :     =item status
600 :    
601 :     Status message. This is sent as part of the status code.
602 :    
603 :     =back
604 :    
605 :     =cut
606 :    
607 :     sub SendError {
608 :     # Get the parameters.
609 :     my ($message, $status) = @_;
610 :     Trace("Error \"$status\" $message") if T(2);
611 : parrello 1.30 # Check for a DBserver error. These can be retried and get a special status
612 :     # code.
613 :     my $realStatus;
614 :     if ($message =~ /DBServer Error:\s+/) {
615 :     $realStatus = "503 $status";
616 :     } else {
617 :     $realStatus = "500 $status";
618 :     }
619 : parrello 1.10 # Print the header and the status message.
620 :     print CGI::header(-type => 'text/plain',
621 : parrello 1.30 -status => $realStatus);
622 : parrello 1.10 # Print the detailed message.
623 :     print $message;
624 :     }
625 :    
626 :    
627 : disz 1.31 1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3