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

Diff of /FigKernelPackages/Tracer.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.84, Thu May 3 12:28:00 2007 UTC revision 1.126, Wed Dec 16 20:00:53 2009 UTC
# Line 1  Line 1 
1  #  # -*- perl -*-
2    ########################################################################
3  # Copyright (c) 2003-2006 University of Chicago and Fellowship  # Copyright (c) 2003-2006 University of Chicago and Fellowship
4  # for Interpretations of Genomes. All Rights Reserved.  # for Interpretations of Genomes. All Rights Reserved.
5  #  #
# Line 13  Line 14 
14  # at info@ci.uchicago.edu or the Fellowship for Interpretation of  # at info@ci.uchicago.edu or the Fellowship for Interpretation of
15  # Genomes at veronika@thefig.info or download a copy from  # Genomes at veronika@thefig.info or download a copy from
16  # http://www.theseed.org/LICENSE.TXT.  # http://www.theseed.org/LICENSE.TXT.
17  #  ########################################################################
18    
19  package Tracer;  package Tracer;
20    
     require Exporter;  
     @ISA = ('Exporter');  
     @EXPORT = qw(Trace T TSetup QTrace Confess Cluck Min Max Assert Open OpenDir TICK StandardSetup EmergencyKey ETracing ScriptSetup ScriptFinish Insure ChDir Emergency);  
     @EXPORT_OK = qw(GetFile GetOptions Merge MergeOptions ParseCommand ParseRecord UnEscape Escape);  
21      use strict;      use strict;
22      use Carp qw(longmess croak);      use base qw(Exporter);
23        use vars qw(@EXPORT @EXPORT_OK);
24        @EXPORT = qw(Trace T TSetup QTrace Confess MemTrace Cluck Min Max Assert Open OpenDir TICK StandardSetup EmergencyKey ETracing Constrain Insure ChDir Emergency Warn TraceDump IDHASH);
25        @EXPORT_OK = qw(GetFile GetOptions Merge MergeOptions ParseCommand ParseRecord UnEscape Escape PrintLine PutLine);
26        use Carp qw(longmess croak carp);
27      use CGI;      use CGI;
28      use Cwd;      use Cwd;
29      use FIG_Config;      use FIG_Config;
# Line 35  Line 36 
36      use Time::HiRes 'gettimeofday';      use Time::HiRes 'gettimeofday';
37      use URI::Escape;      use URI::Escape;
38      use Time::Local;      use Time::Local;
39        use POSIX qw(strftime);
40        use Time::Zone;
41        use Fcntl qw(:DEFAULT :flock);
42        use Data::Dumper;
43    
44    
45  =head1 Tracing and Debugging Helpers  =head1 Tracing and Debugging Helpers
46    
# Line 159  Line 165 
165    
166  Sometimes, you need a way for tracing to happen automatically without putting parameters  Sometimes, you need a way for tracing to happen automatically without putting parameters
167  in a form or on the command line. Emergency tracing does this. You invoke emergency tracing  in a form or on the command line. Emergency tracing does this. You invoke emergency tracing
168  from the debug form, which is accessed from I<MySeedInstance>C</FIG/Html/SetPassword.html>.  from the debug form, which is accessed from the [[DebugConsole]]. Emergency tracing requires
169  Emergency tracing requires you specify a tracing key. For command-line tools, the key is  that you specify a tracing key. For command-line tools, the key is
170  taken from the C<TRACING> environment variable. For web services, the key is taken from  taken from the C<TRACING> environment variable. For web services, the key is taken from
171  a cookie. Either way, the key tells the tracing facility who you are, so that you control  a cookie. Either way, the key tells the tracing facility who you are, so that you control
172  the tracing in your environment without stepping on other users.  the tracing in your environment without stepping on other users.
# Line 183  Line 189 
189    
190  The web script will look for the tracing key in the cookies, and the command-line  The web script will look for the tracing key in the cookies, and the command-line
191  script will look for it in the C<TRACING> environment variable. If you are  script will look for it in the C<TRACING> environment variable. If you are
192  using the L</StandardScript> or L</StandardSetup> methods, emergency tracing  using the L</StandardSetup> method or a [[WebApplication]], emergency tracing
193  will be configured automatically.  will be configured automatically.
194    
 NOTE: to configure emergency tracing from the command line instead of the Debugging  
 Control Panel (see below), use the C<trace.pl> script.  
   
 =head3 Debugging Control Panel  
   
 The debugging control panel provides several tools to assist in development of  
 SEED and Sprout software. You access the debugging control panel from the URL  
 C</FIG/Html/SetPassword.html> in whichever seed instance you're using. (So,  
 for example, the panel access point for the development NMPDR system is  
 C<http://web-1.nmpdr.org/next/FIG/Html/SetPassword.html>. Contact Bruce to  
 find out what the password is. From this page, you can also specify a tracing  
 key. If you don't specify a key, one will be generated for you.  
   
 =head4 Emergency Tracing Form  
   
 At the bottom of the debugging control panel is a form that allows you to  
 specify a trace level and tracing categories. Special and common categories  
 are listed with check boxes. You can hold your mouse over a check box to see  
 what its category does. In general, however, a category name is the same as  
 the name of the package in which the trace message occurs.  
   
 Additional categories can be entered in an input box, delimited by spaces or commas.  
   
 The B<Activate> button turns on Emergency tracing at the level you specify with the  
 specified categories active. The B<Terminate> button turns tracing off. The  
 B<Show File> button displays the current contents of the trace file. The tracing  
 form at the bottom of the control panel is designed for emergency tracing, so it  
 will only affect programs that call L</ETracing>, L</StandardScript>,  
 or L</StandardSetup>.  
   
 =head4 Script Form  
   
 The top form of the debugging control panel allows you to enter a tiny script and  
 have the output generated in a formatted table. Certain object variables are  
 predefined in the script, including a FIG object (C<$fig>), a CGI object (C<$cgi>),  
 and-- if Sprout is active-- Sprout (C<$sprout>) and SFXlate (C<$sfx>) objects.  
   
 The last line of the script must be a scalar, but it can be a reference to a hash,  
 a list, a list of lists, and various other combinations. If you select the appropriate  
 data type in the dropdown box, the output will be formatted accordingly. The form  
 also has controls for specifying tracing. These controls override any emergency  
 tracing in effect.  
   
 =head4 Database Query Forms  
   
 The forms between the script form and the emergency tracing form allow you to  
 make queries against the database. The FIG query form allows simple queries against  
 a single FIG table. The Sprout query form uses the B<GetAll> method to do a  
 multi-table query against the Sprout database. B<GetAll> is located in the B<ERDB>  
 package, and it takes five parameters.  
   
     GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count);  
   
 Each of the five parameters corresponds to a text box on the query form:  
   
 =over 4  
   
 =item Objects  
   
 Comma-separated list containing the names of the entity and relationship objects to be retrieved.  
   
 =item Filter  
   
 WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can  
 be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form  
 B<I<objectName>(I<fieldName>)> or B<$I<number>(I<fieldName>)> where I<fieldName> is the name of a  
 field, I<objectName> is the name of the entity or relationship object containing the field, and  
 I<number> is the 1-based position of the object in the object list. Any parameters  
 specified in the filter clause should be specified in the B<Params> field.  
 The fields in a filter clause can come from primary entity relations,  
 relationship relations, or secondary entity relations; however, all of the  
 entities and relationships involved must be included in the list of object names.  
   
 =item Params  
   
 List of the parameters to be substituted in for the parameters marks in the filter clause. This  
 is a comma-separated list without any quoting or escaping.  
   
 =item fields  
   
 Comma-separated list of the fields to be returned in each element of the list returned. Fields  
 are specified in the same manner as in the filter clause.  
   
 =item count  
   
 Maximum number of records to return. If omitted or 0, all available records will be returned.  
   
 =back  
   
 B<GetAll> automatically joins together the entities and relationships listed in the object  
 names. This simplifies the coding of the filter clause, but it means that some queries are  
 not possible, since they cannot be expressed in a linear sequence of joins. This is a limitation  
 that has yet to be addressed.  
   
195  =cut  =cut
196    
197  # Declare the configuration variables.  # Declare the configuration variables.
198    
199  my $Destination = "NONE";   # Description of where to send the trace output.  my $Destination = "WARN";   # Description of where to send the trace output.
200  my $TeeFlag = 0;            # TRUE if output is going to a file and to the  my $TeeFlag = 0;            # TRUE if output is going to a file and to the
201                              # standard output                              # standard output
202  my %Categories = ( main => 1 );  my %Categories = ( main => 1 );
203                              # hash of active category names                              # hash of active category names
204    my @LevelNames = qw(error warn notice info detail);
205  my $TraceLevel = 0;         # trace level; a higher trace level produces more  my $TraceLevel = 0;         # trace level; a higher trace level produces more
206                              # messages                              # messages
207  my @Queue = ();             # queued list of trace messages.  my @Queue = ();             # queued list of trace messages.
208  my $LastCategory = "main";  # name of the last category interrogated  my $LastCategory = "main";  # name of the last category interrogated
209    my $LastLevel = 0;          # level of the last test call
210  my $SetupCount = 0;         # number of times TSetup called  my $SetupCount = 0;         # number of times TSetup called
211  my $AllTrace = 0;           # TRUE if we are tracing all categories.  my $AllTrace = 0;           # TRUE if we are tracing all categories.
212    my $SavedCGI;               # CGI object passed to ETracing
213    my $CommandLine;            # Command line passed to StandardSetup
214    my $Confessions = 0;        # confession count
215    umask 2;                    # Fix the damn umask so everything is group-writable.
216    
217    =head2 Tracing Methods
218    
219    =head3 Setups
220    
221        my $count = Tracer::Setups();
222    
223    Return the number of times L</TSetup> has been called.
224    
225    This method allows for the creation of conditional tracing setups where, for example, we
226    may want to set up tracing if nobody else has done it before us.
227    
228    =cut
229    
230  =head2 Public Methods  sub Setups {
231        return $SetupCount;
232    }
233    
234  =head3 TSetup  =head3 TSetup
235    
236  C<< TSetup($categoryList, $target); >>      TSetup($categoryList, $target);
237    
238  This method is used to specify the trace options. The options are stored as package data  This method is used to specify the trace options. The options are stored as package data
239  and interrogated by the L</Trace> and L</T> methods.  and interrogated by the L</Trace> and L</T> methods.
# Line 350  Line 283 
283          }          }
284      }      }
285      # Now we need to process the destination information. The most important special      # Now we need to process the destination information. The most important special
286      # cases are the single ">", which requires we clear the file first, and the      # case is when we're writing to a file. This is indicated by ">" (overwrite) and
287      # "+" prefix which indicates a double echo.      # ">>" (append). A leading "+" for either indicates that we are also writing to
288        # the standard output (tee mode).
289      if ($target =~ m/^\+?>>?/) {      if ($target =~ m/^\+?>>?/) {
290          if ($target =~ m/^\+/) {          if ($target =~ m/^\+/) {
291              $TeeFlag = 1;              $TeeFlag = 1;
292              $target = substr($target, 1);              $target = substr($target, 1);
293          }          }
294          if ($target =~ m/^>[^>]/) {          if ($target =~ m/^>[^>]/) {
295                # We need to initialize the file (which clears it).
296              open TRACEFILE, $target;              open TRACEFILE, $target;
297              print TRACEFILE "[" . Now() . "] <Tracer>: Tracing initialized.\n";              print TRACEFILE "[" . Now() . "] [notice] [Tracer] Tracing initialized.\n";
298              close TRACEFILE;              close TRACEFILE;
299                # Set to append mode now that the file has been cleared.
300              $Destination = ">$target";              $Destination = ">$target";
301          } else {          } else {
302              $Destination = $target;              $Destination = $target;
# Line 372  Line 308 
308      $SetupCount++;      $SetupCount++;
309  }  }
310    
311  =head3 StandardSetup  =head3 SetLevel
312    
313  C<< my ($options, @parameters) = StandardSetup(\@categories, \%options, $parmHelp, @ARGV); >>      Tracer::SetLevel($newLevel);
314    
315  This method performs standard command-line parsing and tracing setup. The return  Modify the trace level. A higher trace level will cause more messages to appear.
 values are a hash of the command-line options and a list of the positional  
 parameters. Tracing is automatically set up and the command-line options are  
 validated.  
316    
317  This is a complex method that does a lot of grunt work. The parameters can  =over 4
 be more easily understood, however, once they are examined individually.  
318    
319  The I<categories> parameter is the most obtuse. It is a reference to a list of  =item newLevel
 special-purpose tracing categories. Most tracing categories are PERL package  
 names. So, for example, if you wanted to turn on tracing inside the B<Sprout>,  
 B<ERDB>, and B<SproutLoad> packages, you would specify the categories  
320    
321      ["Sprout", "SproutLoad", "ERDB"]  Proposed new trace level.
322    
323  This would cause trace messages in the specified three packages to appear in  =back
 the output. There are two special tracing categories that are automatically  
 handled by this method. In other words, if you used L</TSetup> you would need  
 to include these categories manually, but if you use this method they are turned  
 on automatically.  
324    
325  =over 4  =cut
326    
327  =item SQL  sub SetLevel {
328        $TraceLevel = $_[0];
329    }
330    
331  Traces SQL commands and activity.  =head3 ParseDate
332    
333  =item Tracer      my $time = Tracer::ParseDate($dateString);
334    
335  Traces error messages and call stacks.  Convert a date into a PERL time number. This method expects a date-like string
336    and parses it into a number. The string must be vaguely date-like or it will
337    return an undefined value. Our requirement is that a month and day be
338    present and that three pieces of the date string (time of day, month and day,
339    year) be separated by likely delimiters, such as spaces, commas, and such-like.
340    
341  =back  If a time of day is present, it must be in military time with two digits for
342    everything but the hour.
343    
344  C<SQL> is only turned on if the C<-sql> option is specified in the command line.  The year must be exactly four digits.
 The trace level is specified using the C<-trace> command-line option. For example,  
 the following command line for C<TransactFeatures> turns on SQL tracing and runs  
 all tracing at level 3.  
345    
346      TransactFeatures -trace=3 -sql register ../xacts IDs.tbl  Additional stuff can be in the string. We presume it's time zones or weekdays or something
347    equally innocuous. This means, however, that a sufficiently long sentence with date-like
348    parts in it may be interpreted as a date. Hopefully this will not be a problem.
349    
350  Standard tracing is output to the standard output and echoed to the file  It should be guaranteed that this method will parse the output of the L</Now> function.
 C<trace>I<$$>C<.log> in the FIG temporary directory, where I<$$> is the  
 process ID. You can also specify the C<user> parameter to put a user ID  
 instead of a process ID in the trace file name. So, for example  
351    
352  The default trace level is 2. To get all messages, specify a trace level of 4.  The parameters are as follows.
 For a genome-by-genome update, use 3.  
353    
354      TransactFeatures -trace=3 -sql -user=Bruce register ../xacts IDs.tbl  =over 4
355    
356  would send the trace output to C<traceBruce.log> in the temporary directory.  =item dateString
357    
358  The I<options> parameter is a reference to a hash containing the command-line  The date string to convert.
 options, their default values, and an explanation of what they mean. Command-line  
 options may be in the form of switches or keywords. In the case of a switch, the  
 option value is 1 if it is specified and 0 if it is not specified. In the case  
 of a keyword, the value is separated from the option name by an equal sign. You  
 can see this last in the command-line example above.  
359    
360  You can specify a different default trace level by setting C<$options->{trace}>  =item RETURN
 prior to calling this method.  
361    
362  An example at this point would help. Consider, for example, the command-line utility  Returns a PERL time, that is, a number of seconds since the epoch, or C<undef> if
363  C<TransactFeatures>. It accepts a list of positional parameters plus the options  the date string is invalid. A valid date string must contain a month and day.
 C<safe>, C<noAlias>, C<start>, and C<tblFiles>. To start up this command, we execute  
 the following code.  
364    
365      my ($options, @parameters) = Tracer::StandardSetup(["DocUtils"],  =back
                         { safe => [0, "use database transactions"],  
                           noAlias => [0, "do not expect aliases in CHANGE transactions"],  
                           start => [' ', "start with this genome"],  
                           tblFiles => [0, "output TBL files containing the corrected IDs"] },  
                         "<command> <transactionDirectory> <IDfile>",  
                       @ARGV);  
366    
367    =cut
368    
369  The call to C<ParseCommand> specifies the default values for the options and  # Universal month conversion table.
370  stores the actual options in a hash that is returned as C<$options>. The  use constant MONTHS => {    Jan =>  0, January   =>  0, '01' =>  0,  '1' =>  0,
371  positional parameters are returned in C<@parameters>.                              Feb =>  1, February  =>  1, '02' =>  1,  '2' =>  1,
372                                Mar =>  2, March     =>  2, '03' =>  2,  '3' =>  2,
373                                Apr =>  3, April     =>  3, '04' =>  3,  '4' =>  3,
374                                May =>  4, May       =>  4, '05' =>  4,  '5' =>  4,
375                                Jun =>  5, June      =>  5, '06' =>  5,  '6' =>  5,
376                                Jul =>  6, July      =>  6, '07' =>  6,  '7' =>  6,
377                                Aug =>  7, August    =>  7, '08' =>  7,  '8' =>  7,
378                                Sep =>  8, September =>  8, '09' =>  8,  '9' =>  8,
379                                Oct =>  9, October  =>   9, '10' =>  9,
380                                Nov => 10, November =>  10, '11' => 10,
381                                Dec => 11, December =>  11, '12' => 11
382                            };
383    
384  The following is a sample command line for C<TransactFeatures>.  sub ParseDate {
385        # Get the parameters.
386        my ($dateString) = @_;
387        # Declare the return variable.
388        my $retVal;
389        # Find the month and day of month. There are two ways that can happen. We check for the
390        # numeric style first. That way, if the user's done something like "Sun 12/22", then we
391        # won't be fooled into thinking the month is Sunday.
392        if ($dateString =~ m#\b(\d{1,2})/(\d{1,2})\b# || $dateString =~ m#\b(\w+)\s(\d{1,2})\b#) {
393            my ($mon, $mday) = (MONTHS->{$1}, $2);
394            # Insist that the month and day are valid.
395            if (defined($mon) && $2 >= 1 && $2 <= 31) {
396                # Find the time.
397                my ($hour, $min, $sec) = (0, 0, 0);
398                if ($dateString =~ /\b(\d{1,2}):(\d{2}):(\d{2})\b/) {
399                    ($hour, $min, $sec) = ($1, $2, $3);
400                }
401                # Find the year.
402                my $year;
403                if ($dateString =~ /\b(\d{4})\b/) {
404                    $year = $1;
405                } else {
406                    # Get the default year, which is this one. Note we must convert it to
407                    # the four-digit value expected by "timelocal".
408                    (undef, undef, undef, undef, undef, $year) = localtime();
409                    $year += 1900;
410                }
411                $retVal = timelocal($sec, $min, $hour, $mday, $mon, $year);
412            }
413        }
414        # Return the result.
415        return $retVal;
416    }
417    
418      TransactFeatures -trace=2 -noAlias register ../xacts IDs.tbl  =head3 LogErrors
419    
420  Single and double hyphens are equivalent. So, you could also code the      Tracer::LogErrors($fileName);
 above command as  
421    
422      TransactFeatures --trace=2 --noAlias register ../xacts IDs.tbl  Route the standard error output to a log file.
423    
424  In this case, C<register>, C<../xacts>, and C<IDs.tbl> are the positional  =over 4
 parameters, and would find themselves in I<@parameters> after executing the  
 above code fragment. The tracing would be set to level 2, and the categories  
 would be C<Tracer>, and <DocUtils>. C<Tracer> is standard,  
 and C<DocUtils> was included because it came in within the first parameter  
 to this method. The I<$options> hash would be  
425    
426      { trace => 2, sql => 0, safe => 0,  =item fileName
       noAlias => 1, start => ' ', tblFiles => 0 }  
427    
428  Use of C<StandardSetup> in this way provides a simple way of performing  Name of the file to receive the error output.
 standard tracing setup and command-line parsing. Note that the caller is  
 not even aware of the command-line switches C<-trace> and C<-sql>, which  
 are used by this method to control the tracing. If additional tracing features  
 need to be added in the future, they can be processed by this method without  
 upsetting the command-line utilities.  
429    
430  If the C<background> option is specified on the command line, then the  =back
 standard and error outputs will be directed to files in the temporary  
 directory, using the same suffix as the trace file. So, if the command  
 line specified  
431    
432      -user=Bruce -background  =cut
433    
434  then the trace output would go to C<traceBruce.log>, the standard output to  sub LogErrors {
435  C<outBruce.log>, and the error output to C<errBruce.log>. This is designed to      # Get the file name.
436  simplify starting a command in the background.      my ($fileName) = @_;
437        # Open the file as the standard error output.
438        open STDERR, '>', $fileName;
439    }
440    
441  The user name is also used as the tracing key for L</Emergency Tracing>.  =head3 Trace
 Specifying a value of C<E> for the trace level causes emergency tracing to  
 be used instead of custom tracing. If the user name is not specified,  
 the tracing key is taken from the C<Tracing> environment variable. If there  
 is no value for that variable, the tracing key will be computed from the PID.  
442    
443  Finally, if the special option C<-help> is specified, the option      Trace($message);
 names will be traced at level 0 and the program will exit without processing.  
 This provides a limited help capability. For example, if the user enters  
444    
445      TransactFeatures -help  Write a trace message to the target location specified in L</TSetup>. If there has not been
446    any prior call to B<TSetup>.
447    
448  he would see the following output.  =over 4
449    
450      TransactFeatures [options] <command> <transactionDirectory> <IDfile>  =item message
         -trace    tracing level (default E)  
         -sql      trace SQL commands  
         -safe     use database transactions  
         -noAlias  do not expect aliases in CHANGE transactions  
         -start    start with this genome  
         -tblFiles output TBL files containing the corrected IDs  
451    
452  The caller has the option of modifying the tracing scheme by placing a value  Message to write.
 for C<trace> in the incoming options hash. The default value can be overridden,  
 or the tracing to the standard output can be turned off by suffixing a minus  
 sign to the trace level. So, for example,  
453    
454      { trace => [0, "tracing level (default 0)"],  =back
        ...  
455    
456  would set the default trace level to 0 instead of E, while  =cut
457    
458      { trace => ["2-", "tracing level (default 2)"],  sub Trace {
459         ...      # Get the parameters.
460        my ($message) = @_;
461        # Strip off any line terminators at the end of the message. We will add
462        # new-line stuff ourselves.
463        my $stripped = Strip($message);
464        # Compute the caller information.
465        my ($callPackage, $callFile, $callLine) = caller();
466        my $callFileTitle = basename($callFile);
467        # Check the caller.
468        my $callerInfo = ($callFileTitle ne "Tracer.pm" ? " [$callFileTitle $callLine]" : "");
469        # Get the timestamp.
470        my $timeStamp = Now();
471        # Build the prefix.
472        my $level = $LevelNames[$LastLevel] || "($LastLevel)";
473        my $prefix = "[$timeStamp] [$level] [$LastCategory]$callerInfo";
474        # Format the message.
475        my $formatted = "$prefix $stripped";
476        # Process according to the destination.
477        if ($Destination eq "TEXT") {
478            # Write the message to the standard output.
479            print "$formatted\n";
480        } elsif ($Destination eq "ERROR") {
481            # Write the message to the error output. Here, we want our prefix fields.
482            print STDERR "$formatted\n";
483        } elsif ($Destination eq "WARN") {
484            # Emit the message to the standard error output. It is presumed that the
485            # error logger will add its own prefix fields, the notable exception being
486            # the caller info.
487            print STDERR "$callerInfo$stripped\n";
488        } elsif ($Destination eq "QUEUE") {
489            # Push the message into the queue.
490            push @Queue, "$formatted";
491        } elsif ($Destination eq "HTML") {
492            # Convert the message to HTML.
493            my $escapedMessage = CGI::escapeHTML($stripped);
494            # The stuff after the first line feed should be pre-formatted.
495            my @lines = split /\s*\n/, $escapedMessage;
496            # Get the normal portion.
497            my $line1 = shift @lines;
498            print "<p>$timeStamp $LastCategory $LastLevel: $line1</p>\n";
499            if (@lines) {
500                print "<pre>" . join("\n", @lines, "</pre>");
501            }
502        } elsif ($Destination =~ m/^>>/) {
503            # Write the trace message to an output file.
504            open(TRACING, $Destination) || die "Tracing open for \"$Destination\" failed: $!";
505            # Lock the file.
506            flock TRACING, LOCK_EX;
507            print TRACING "$formatted\n";
508            close TRACING;
509            # If the Tee flag is on, echo it to the standard output.
510            if ($TeeFlag) {
511                print "$formatted\n";
512            }
513        }
514    }
515    
516  would set the default to 2, but trace only to the log file, not to the  =head3 MemTrace
 standard output.  
517    
518  The parameters to this method are as follows.      MemTrace($message);
519    
520    Output a trace message that includes memory size information.
521    
522  =over 4  =over 4
523    
524  =item categories  =item message
525    
526  Reference to a list of tracing category names. These should be names of  Message to display. The message will be followed by a sentence about the memory size.
 packages whose internal workings will need to be debugged to get the  
 command working.  
527    
528  =item options  =back
529    
530  Reference to a hash containing the legal options for the current command mapped  =cut
 to their default values and descriptions. The user can override the defaults  
 by specifying the options as command-line switches prefixed by a hyphen.  
 Tracing-related options may be added to this hash. If the C<-h> option is  
 specified on the command line, the option descriptions will be used to  
 explain the options. To turn off tracing to the standard output, add a  
 minus sign to the value for C<trace> (see above).  
531    
532  =item parmHelp  sub MemTrace {
533        # Get the parameters.
534        my ($message) = @_;
535        my $memory = GetMemorySize();
536        Trace("$message $memory in use.");
537    }
538    
 A string that vaguely describes the positional parameters. This is used  
 if the user specifies the C<-h> option.  
539    
540  =item argv  =head3 TraceDump
541    
542        TraceDump($title, $object);
543    
544    Dump an object to the trace log. This method simply calls the C<Dumper>
545    function, but routes the output to the trace log instead of returning it
546    as a string. The output is arranged so that it comes out monospaced when
547    it appears in an HTML trace dump.
548    
549    =over 4
550    
551    =item title
552    
553    Title to give to the object being dumped.
554    
555    =item object
556    
557    Reference to a list, hash, or object to dump.
558    
559    =back
560    
561    =cut
562    
563    sub TraceDump {
564        # Get the parameters.
565        my ($title, $object) = @_;
566        # Trace the object.
567        Trace("Object dump for $title:\n" . Dumper($object));
568    }
569    
570    =head3 T
571    
572        my $switch = T($category, $traceLevel);
573    
574        or
575    
576        my $switch = T($traceLevel);
577    
578    Return TRUE if the trace level is at or above a specified value and the specified category
579    is active, else FALSE. If no category is specified, the caller's package name is used.
580    
581    =over 4
582    
583    =item category
584    
585    Category to which the message belongs. If not specified, the caller's package name is
586    used.
587    
588    =item traceLevel
589    
590    Relevant tracing level.
591    
592    =item RETURN
593    
594    TRUE if a message at the specified trace level would appear in the trace, else FALSE.
595    
596    =back
597    
598    =cut
599    
600    sub T {
601        # Declare the return variable.
602        my $retVal = 0;
603        # Only proceed if tracing is turned on.
604        if ($Destination ne "NONE") {
605            # Get the parameters.
606            my ($category, $traceLevel) = @_;
607            if (!defined $traceLevel) {
608                # Here we have no category, so we need to get the calling package.
609                # The calling package is normally the first parameter. If it is
610                # omitted, the first parameter will be the tracelevel. So, the
611                # first thing we do is shift the so-called category into the
612                # $traceLevel variable where it belongs.
613                $traceLevel = $category;
614                my ($package, $fileName, $line) = caller;
615                # If there is no calling package, we default to "main".
616                if (!$package) {
617                    $category = "main";
618                } else {
619                    my @cats = split /::/, $package;
620                    $category = $cats[$#cats];
621                }
622            }
623            # Save the category name and level.
624            $LastCategory = $category;
625            $LastLevel = $traceLevel;
626            # Convert it to lower case before we hash it.
627            $category = lc $category;
628            # Validate the trace level.
629            if (ref $traceLevel) {
630                Confess("Bad trace level.");
631            } elsif (ref $TraceLevel) {
632                Confess("Bad trace config.");
633            }
634            # Make the check. Note that level 0 shows even if the category is turned off.
635            $retVal = ($traceLevel <= $TraceLevel && ($traceLevel == 0 || $AllTrace || exists $Categories{$category}));
636        }
637        # Return the computed result.
638        return $retVal;
639    }
640    
641    =head3 QTrace
642    
643        my $data = QTrace($format);
644    
645    Return the queued trace data in the specified format.
646    
647    =over 4
648    
649    =item format
650    
651    C<html> to format the data as an HTML list, C<text> to format it as straight text.
652    
653    =back
654    
655    =cut
656    
657    sub QTrace {
658        # Get the parameter.
659        my ($format) = @_;
660        # Create the return variable.
661        my $retVal = "";
662        # Only proceed if there is an actual queue.
663        if (@Queue) {
664            # Process according to the format.
665            if ($format =~ m/^HTML$/i) {
666                # Convert the queue into an HTML list.
667                $retVal = "<ul>\n";
668                for my $line (@Queue) {
669                    my $escapedLine = CGI::escapeHTML($line);
670                    $retVal .= "<li>$escapedLine</li>\n";
671                }
672                $retVal .= "</ul>\n";
673            } elsif ($format =~ m/^TEXT$/i) {
674                # Convert the queue into a list of text lines.
675                $retVal = join("\n", @Queue) . "\n";
676            }
677            # Clear the queue.
678            @Queue = ();
679        }
680        # Return the formatted list.
681        return $retVal;
682    }
683    
684    =head3 Confess
685    
686        Confess($message);
687    
688    Trace the call stack and abort the program with the specified message. When used with
689    the OR operator and the L</Assert> method, B<Confess> can function as a debugging assert.
690    So, for example
691    
692        Assert($recNum >= 0) || Confess("Invalid record number $recNum.");
693    
694    Will abort the program with a stack trace if the value of C<$recNum> is negative.
695    
696    =over 4
697    
698    =item message
699    
700    Message to include in the trace.
701    
702    =back
703    
704    =cut
705    
706    sub Confess {
707        # Get the parameters.
708        my ($message) = @_;
709        # Set up the category and level.
710        $LastCategory = "(confess)";
711        $LastLevel = 0;
712        # Trace the call stack.
713        Cluck($message);
714        # Increment the confession count.
715        $Confessions++;
716        # Abort the program.
717        croak(">>> $message");
718    }
719    
720    =head3 Confessions
721    
722        my $count = Tracer::Confessions();
723    
724    Return the number of calls to L</Confess> by the current task.
725    
726    =cut
727    
728    sub Confessions {
729        return $Confessions;
730    }
731    
732    
733    =head3 SaveCGI
734    
735        Tracer::SaveCGI($cgi);
736    
737    This method saves the CGI object but does not activate emergency tracing.
738    It is used to allow L</Warn> to work in situations where emergency
739    tracing is contra-indicated (e.g. the wiki).
740    
741    =over 4
742    
743    =item cgi
744    
745    Active CGI query object.
746    
747    =back
748    
749    =cut
750    
751    sub SaveCGI {
752        $SavedCGI = $_[0];
753    }
754    
755    =head3 Warn
756    
757        Warn($message, @options);
758    
759    This method traces an important message. If an RSS feed is configured
760    (via I<FIG_Config::error_feed>) and the tracing destination is C<WARN>,
761    then the message will be echoed to the feed. In general, a tracing
762    destination of C<WARN> indicates that the caller is running as a web
763    service in a production environment; however, this is not a requirement.
764    
765    To force warnings into the RSS feed even when the tracing destination
766    is not C<WARN>, simply specify the C<Feed> tracing module. This can be
767    configured automatically when L</StandardSetup> is used.
768    
769    The L</Cluck> method calls this one for its final message. Since
770    L</Confess> calls L</Cluck>, this means that any error which is caught
771    and confessed will put something in the feed. This insures that someone
772    will be alerted relatively quickly when a failure occurs.
773    
774    =over 4
775    
776    =item message
777    
778    Message to be traced.
779    
780    =item options
781    
782    A list containing zero or more options.
783    
784    =back
785    
786    The permissible options are as follows.
787    
788    =over 4
789    
790    =item noStack
791    
792    If specified, then the stack trace is not included in the output.
793    
794    =back
795    
796    =cut
797    
798    sub Warn {
799        # Get the parameters.
800        my $message = shift @_;
801        my %options = map { $_ => 1 } @_;
802        # Save $@;
803        my $savedError = $@;
804        # Trace the message.
805        Trace($message);
806        # This will contain the lock handle. If it's defined, it means we need to unlock.
807        my $lock;
808        # Check for feed forcing.
809        my $forceFeed = exists $Categories{feed};
810        # An error here would be disastrous. Note that if debug mode is specified,
811        # we do this stuff even in a test environment.
812        eval {
813            # Do we need to put this in the RSS feed?
814            if ($FIG_Config::error_feed && ($Destination eq 'WARN' || $forceFeed)) {
815                # Probably. We need to check first, however, to see if it's from an
816                # ignored IP. For non-CGI situations, we default the IP to the self-referent.
817                my $key = "127.0.0.1";
818                if (defined $SavedCGI) {
819                    # Get the IP address.
820                    $key = $ENV{HTTP_X_FORWARDED_FOR} || $ENV{REMOTE_ADDR};
821                }
822                # Is the IP address in the ignore list?
823                my $found = scalar(grep { $_ eq $key } @FIG_Config::error_ignore_ips);
824                if (! $found) {
825                    # No. We're good. We now need to compute the date, the link, and the title.
826                    # First, the date, in a very specific format.
827                    my $date = strftime("%a, %02e %b %H:%M:%S %Y ", localtime) .
828                        (tz_local_offset() / 30);
829                    # Environment data goes in here. We start with the date.
830                    my $environment = "$date.  ";
831                    # If we need to recap the message (because it's too long to be a title), we'll
832                    # put it in here.
833                    my $recap;
834                    # Copy the message and remove excess space.
835                    my $title = $message;
836                    $title =~ s/\s+/ /gs;
837                    # If it's too long, we have to split it up.
838                    if (length $title > 60) {
839                        # Put the full message in the environment string.
840                        $recap = $title;
841                        # Excerpt it as the title.
842                        $title = substr($title, 0, 50) . "...";
843                    }
844                    # If we have a CGI object, then this is a web error. Otherwise, it's
845                    # command-line.
846                    if (defined $SavedCGI) {
847                        # We're in a web service. The environment is the user's IP, and the link
848                        # is the URL that got us here.
849                        $environment .= "Event Reported at IP address $key process $$.";
850                        my $url = $SavedCGI->self_url();
851                        # We need the user agent string and (if available) the referrer.
852                        # The referrer will be the link.
853                        $environment .= " User Agent $ENV{HTTP_USER_AGENT}";
854                        if ($ENV{HTTP_REFERER}) {
855                            my $link = $ENV{HTTP_REFERER};
856                            $environment .= " referred from <a href=\"$link\">$link</a>.";
857                        } else {
858                            $environment .= " referrer unknown.";
859                        }
860                        # Close off the sentence with the original link.
861                        $environment .= " URL of event is <a href=\"$url\">$url</a>.";
862                    } else {
863                        # No CGI object, so we're a command-line tool. Use the tracing
864                        # key and the PID as the user identifier, and add the command.
865                        my $key = EmergencyKey();
866                        $environment .= "Event Reported by $key process $$.";
867                        if ($CommandLine) {
868                            # We're in a StandardSetup script, so we have the real command line.
869                            $environment .= "\n<pre>" . CGI::escapeHTML($CommandLine) . "</pre>\n";
870                        } elsif ($ENV{_}) {
871                            # We're in a BASH script, so the command has been stored in the _ variable.
872                            $environment .= "  Command = " . CGI::escapeHTML($ENV{_}) . "\n";
873                        }
874                    }
875                    # Build a GUID. We use the current time, the title, and the process ID,
876                    # then digest the result.
877                    my $guid = Digest::MD5::md5_base64(gettimeofday(), $title, $$);
878                    # Finally, the description. This is a stack trace plus various environmental stuff.
879                    # The trace is optional.
880                    my $stackTrace;
881                    if ($options{noStack}) {
882                        $stackTrace = "";
883                    } else {
884                        my @trace = LongMess();
885                        # Only proceed if we got something back.
886                        if (scalar(@trace) > 0) {
887                            $trace[0] =~ s/Tracer::Warn.+?called/Event occurred/;
888                            $stackTrace = "Stack trace:<pre>" . join("\n", @trace, "</pre>");
889                        }
890                    }
891                    # We got the stack trace. Now it's time to put it all together.
892                    # We have a goofy thing here in that we need to HTML-escape some sections of the description
893                    # twice. They will be escaped once here, and then once when written by XML::Simple. They are
894                    # unescaped once when processed by the RSS reader, and stuff in the description is treated as
895                    # HTML. So, anything escaped here is treated as a literal when viewed in the RSS reader, but
896                    # our <br>s and <pre>s are used to format the description.
897                    $recap = (defined $recap ? "<em>" . CGI::escapeHTML($recap) . "</em><br /><br />" : "");
898                    my $description = "$recap$environment  $stackTrace";
899                    # Okay, we have all the pieces. Create a hash of the new event.
900                    my $newItem = { title => $title,
901                                    description => $description,
902                                    category => $LastCategory,
903                                    pubDate => $date,
904                                    guid => $guid,
905                                  };
906                    # We need XML capability for this.
907                    require XML::Simple;
908                    # The RSS document goes in here.
909                    my $rss;
910                    # Get the name of the RSS file. It's in the FIG temporary directory.
911                    my $fileName = "$FIG_Config::temp/$FIG_Config::error_feed";
912                    # Open the config file and lock it.
913                    $lock = Open(undef, "<$FIG_Config::fig_disk/config/FIG_Config.pm");
914                    flock $lock, LOCK_EX;
915                    # Does it exist?
916                    if (-s $fileName) {
917                        # Slurp it in.
918                        $rss = XML::Simple::XMLin($fileName, ForceArray => ['item']);
919                    } else {
920                        my $size = -s $fileName;
921                        # Create an empty channel.
922                        $rss = {
923                            channel => {
924                                title => 'NMPDR Warning Feed',
925                                link => "$FIG_Config::temp_url/$FIG_Config::error_feed",
926                                description => "Important messages regarding the status of the NMPDR.",
927                                generator => "NMPDR Trace Facility",
928                                docs => "http://blogs.law.harvard.edu/tech/rss",
929                                item => []
930                            },
931                        };
932                    }
933                    # Get the channel object.
934                    my $channel = $rss->{channel};
935                    # Update the last-build date.
936                    $channel->{lastBuildDate} = $date;
937                    # Get the item array.
938                    my $items = $channel->{item};
939                    # Insure it has only 100 entries.
940                    while (scalar @{$items} > 100) {
941                        pop @{$items};
942                    }
943                    # Add our new item at the front.
944                    unshift @{$items}, $newItem;
945                    # Create the XML. Note we do not include the root or the declaration. XML Simple can't handle
946                    # the requirements for those.
947                    my $xml = XML::Simple::XMLout($channel, NoAttr => 1, RootName => 'channel', XmlDecl => '');
948                    # Here we put in the root and declaration. The problem is that the root has to have the version attribute
949                    # in it. So, we suppress the root and do it by hand, and that requires suppressing the declaration, too.
950                    $xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<rss version=\"2.0\">$xml\n</rss>";
951                    # We don't use Open here because we can't afford an error.
952                    if (open XMLOUT, ">$fileName") {
953                        print XMLOUT $xml;
954                        close XMLOUT;
955                    }
956                }
957            }
958        };
959        if ($@) {
960            # If the feed failed, we need to know why. The error will be traced, but this method will not be involved
961            # (which is a good thing).
962            my $error = $@;
963            Trace("Feed Error: $error") if T(Feed => 0);
964        }
965        # Be sure to unlock.
966        if ($lock) {
967            flock $lock, LOCK_UN;
968            undef $lock;
969        }
970        # Restore the error message.
971        $@ = $savedError;
972    }
973    
974    
975    
976    
977    =head3 Assert
978    
979        Assert($condition1, $condition2, ... $conditionN);
980    
981    Return TRUE if all the conditions are true. This method can be used in conjunction with
982    the OR operator and the L</Confess> method as a debugging assert.
983    So, for example
984    
985        Assert($recNum >= 0) || Confess("Invalid record number $recNum.");
986    
987    Will abort the program with a stack trace if the value of C<$recNum> is negative.
988    
989    =cut
990    sub Assert {
991        my $retVal = 1;
992        LOOP: for my $condition (@_) {
993            if (! $condition) {
994                $retVal = 0;
995                last LOOP;
996            }
997        }
998        return $retVal;
999    }
1000    
1001    =head3 Cluck
1002    
1003        Cluck($message);
1004    
1005    Trace the call stack. Note that for best results, you should qualify the call with a
1006    trace condition. For example,
1007    
1008        Cluck("Starting record parse.") if T(3);
1009    
1010    will only trace the stack if the trace level for the package is 3 or more.
1011    
1012    =over 4
1013    
1014    =item message
1015    
1016    Message to include in the trace.
1017    
1018    =back
1019    
1020    =cut
1021    
1022    sub Cluck {
1023        # Get the parameters.
1024        my ($message) = @_;
1025        # Trace what's happening.
1026        Trace("Stack trace for event: $message");
1027        # Get the stack trace.
1028        my @trace = LongMess();
1029        # Convert the trace to a series of messages.
1030        for my $line (@trace) {
1031            # Replace the tab at the beginning with spaces.
1032            $line =~ s/^\t/    /;
1033            # Trace the line.
1034            Trace($line);
1035        }
1036        # Issue a warning. This displays the event message and inserts it into the RSS error feed.
1037        Warn($message);
1038    }
1039    
1040    =head3 LongMess
1041    
1042        my @lines = Tracer::LongMess();
1043    
1044    Return a stack trace with all tracing methods removed. The return will be in the form of a list
1045    of message strings.
1046    
1047    =cut
1048    
1049    sub LongMess {
1050        # Declare the return variable.
1051        my @retVal = ();
1052        my $confession = longmess("");
1053        for my $line (split /\s*\n/, $confession) {
1054            unless ($line =~ /Tracer\.pm/) {
1055                # Here we have a line worth keeping. Push it onto the result list.
1056                push @retVal, $line;
1057            }
1058        }
1059        # Return the result.
1060        return @retVal;
1061    }
1062    
1063  List of command line parameters, including the option switches, which must  =head3 ETracing
1064  precede the positional parameters and be prefixed by a hyphen.  
1065        ETracing($parameter, %options);
1066    
1067    Set up emergency tracing. Emergency tracing is tracing that is turned
1068    on automatically for any program that calls this method. The emergency
1069    tracing parameters are stored in a a file identified by a tracing key.
1070    If this method is called with a CGI object, then the tracing key is
1071    taken from a cookie. If it is called with no parameters, then the tracing
1072    key is taken from an environment variable. If it is called with a string,
1073    the tracing key is that string.
1074    
1075    =over 4
1076    
1077    =item parameter
1078    
1079    A parameter from which the tracing key is computed. If it is a scalar,
1080    that scalar is used as the tracing key. If it is a CGI object, the
1081    tracing key is taken from the C<IP> cookie. If it is omitted, the
1082    tracing key is taken from the C<TRACING> environment variable. If it
1083    is a CGI object and emergency tracing is not on, the C<Trace> and
1084    C<TF> parameters will be used to determine the type of tracing.
1085    
1086    =item options
1087    
1088    Hash of options. The permissible options are given below.
1089    
1090    =over 8
1091    
1092    =item destType
1093    
1094    Emergency tracing destination type to use if no tracing file is found. The
1095    default is C<WARN>.
1096    
1097    =item noParms
1098    
1099    If TRUE, then display of the saved CGI parms is suppressed. The default is FALSE.
1100    
1101    =item level
1102    
1103    The trace level to use if no tracing file is found. The default is C<0>.
1104    
1105    =back
1106    
1107    =cut
1108    
1109    sub ETracing {
1110        # Get the parameter.
1111        my ($parameter, %options) = @_;
1112        # Check for CGI mode.
1113        if (defined $parameter && ref $parameter eq 'CGI') {
1114            $SavedCGI = $parameter;
1115        } else {
1116            $SavedCGI = undef;
1117        }
1118        # Check for the noParms option.
1119        my $noParms = $options{noParms} || 0;
1120        # Get the default tracing information.
1121        my $tracing = $options{level} || 0;
1122        my $dest = $options{destType} || "WARN";
1123        # Check for emergency tracing.
1124        my $tkey = EmergencyKey($parameter);
1125        warn "Tracing key is $tkey.\n"; ##HACK
1126        my $emergencyFile = EmergencyFileName($tkey);
1127        if (-e $emergencyFile) {
1128            # We have the file. Read in the data.
1129            my @tracing = GetFile($emergencyFile);
1130            # Pull off the time limit.
1131            my $expire = shift @tracing;
1132            # Convert it to seconds.
1133            $expire *= 3600;
1134            # Check the file data.
1135            my $stat = stat($emergencyFile);
1136            my ($now) = gettimeofday;
1137            if ($now - $stat->mtime > $expire) {
1138                # Delete the expired file.
1139                unlink $emergencyFile;
1140            } else {
1141                # Emergency tracing is on. Pull off the destination and
1142                # the trace level;
1143                $dest = shift @tracing;
1144                my $level = shift @tracing;
1145                # Insure Tracer is specified.
1146                my %moduleHash = map { $_ => 1 } @tracing;
1147                $moduleHash{Tracer} = 1;
1148                # Set the trace parameter.
1149                $tracing = join(" ", $level, sort keys %moduleHash);
1150            }
1151        }
1152        # Convert the destination to a real tracing destination.
1153        warn "Tracing destination is $dest.\n"; ##HACK
1154        $dest = EmergencyTracingDest($tkey, $dest);
1155        # Setup the tracing we've determined from all the stuff above.
1156        warn "TSetup is \"$tracing\", \"$dest\".\n"; ##HACK
1157        TSetup($tracing, $dest);
1158        # Check to see if we're a web script.
1159        if (defined $SavedCGI) {
1160            # Yes we are. Trace the form and environment data if it's not suppressed.
1161            if (! $noParms) {
1162                TraceParms($SavedCGI);
1163            }
1164            # Check for RAW mode. In raw mode, we print a fake header so that we see everything
1165            # emitted by the script in its raw form.
1166            if (T(Raw => 3)) {
1167                print CGI::header(-type => 'text/plain', -tracing => 'Raw');
1168            }
1169        }
1170    }
1171    
1172    =head3 EmergencyFileName
1173    
1174        my $fileName = Tracer::EmergencyFileName($tkey);
1175    
1176    Return the emergency tracing file name. This is the file that specifies
1177    the tracing information.
1178    
1179    =over 4
1180    
1181    =item tkey
1182    
1183    Tracing key for the current program.
1184    
1185  =item RETURN  =item RETURN
1186    
1187  Returns a list. The first element of the list is the reference to a hash that  Returns the name of the file to contain the emergency tracing information.
1188  maps the command-line option switches to their values. These will either be the  
1189  default values or overrides specified on the command line. The remaining  =back
1190  elements of the list are the position parameters, in order.  
1191    =cut
1192    
1193    sub EmergencyFileName {
1194        # Get the parameters.
1195        my ($tkey) = @_;
1196        # Compute the emergency tracing file name.
1197        return "$FIG_Config::temp/Emergency$tkey.txt";
1198    }
1199    
1200    =head3 EmergencyFileTarget
1201    
1202        my $fileName = Tracer::EmergencyFileTarget($tkey);
1203    
1204    Return the emergency tracing target file name. This is the file that receives
1205    the tracing output for file-based tracing.
1206    
1207    =over 4
1208    
1209    =item tkey
1210    
1211    Tracing key for the current program.
1212    
1213    =item RETURN
1214    
1215    Returns the name of the file to contain the trace output.
1216    
1217    =back
1218    
1219    =cut
1220    
1221    sub EmergencyFileTarget {
1222        # Get the parameters.
1223        my ($tkey) = @_;
1224        # Compute the emergency tracing file name.
1225        return "$FIG_Config::temp/trace$tkey.log";
1226    }
1227    
1228    =head3 EmergencyTracingDest
1229    
1230        my $dest = Tracer::EmergencyTracingDest($tkey, $myDest);
1231    
1232    This method converts an emergency tracing destination to a real
1233    tracing destination. The main difference is that if the
1234    destination is C<FILE> or C<APPEND>, we convert it to file
1235    output. If the destination is C<DUAL>, we convert it to file
1236    and standard output.
1237    
1238    =over 4
1239    
1240    =item tkey
1241    
1242    Tracing key for this environment.
1243    
1244    =item myDest
1245    
1246    Destination from the emergency tracing file.
1247    
1248    =item RETURN
1249    
1250    Returns a destination that can be passed into L</TSetup>.
1251    
1252    =back
1253    
1254    =cut
1255    
1256    sub EmergencyTracingDest {
1257        # Get the parameters.
1258        my ($tkey, $myDest) = @_;
1259        # Declare the return variable.
1260        my $retVal = $myDest;
1261        # Process according to the destination value.
1262        if ($myDest eq 'FILE') {
1263            $retVal = ">" . EmergencyFileTarget($tkey);
1264        } elsif ($myDest eq 'APPEND') {
1265            $retVal = ">>" . EmergencyFileTarget($tkey);
1266        } elsif ($myDest eq 'DUAL') {
1267            $retVal = "+>" . EmergencyFileTarget($tkey);
1268        } elsif ($myDest eq 'WARN') {
1269            $retVal = "WARN";
1270        }
1271        # Return the result.
1272        return $retVal;
1273    }
1274    
1275    =head3 Emergency
1276    
1277        Emergency($key, $hours, $dest, $level, @modules);
1278    
1279    Turn on emergency tracing. This method is normally invoked over the web from
1280    a debugging console, but it can also be called by the C<trace.pl> script.
1281    The caller specifies the duration of the emergency in hours, the desired tracing
1282    destination, the trace level, and a list of the trace modules to activate.
1283    For the length of the duration, when a program in an environment with the
1284    specified tracing key active invokes a Sprout CGI script, tracing will be
1285    turned on automatically. See L</TSetup> for more about tracing setup and
1286    L</ETracing> for more about emergency tracing.
1287    
1288    =over 4
1289    
1290    =item tkey
1291    
1292    The tracing key. This is used to identify the control file and the trace file.
1293    
1294    =item hours
1295    
1296    Number of hours to keep emergency tracing alive.
1297    
1298    =item dest
1299    
1300    Tracing destination. If no path information is specified for a file
1301    destination, it is put in the FIG temporary directory.
1302    
1303    =item level
1304    
1305    Tracing level. A higher level means more trace messages.
1306    
1307    =item modules
1308    
1309    A list of the tracing modules to activate.
1310    
1311    =back
1312    
1313    =cut
1314    
1315    sub Emergency {
1316        # Get the parameters.
1317        my ($tkey, $hours, $dest, $level, @modules) = @_;
1318        # Create the emergency file.
1319        my $specFile = EmergencyFileName($tkey);
1320        my $outHandle = Open(undef, ">$specFile");
1321        print $outHandle join("\n", $hours, $dest, $level, @modules, "");
1322    }
1323    
1324    =head3 EmergencyKey
1325    
1326        my $tkey = EmergencyKey($parameter);
1327    
1328    Return the Key to be used for emergency tracing. This could be an IP address,
1329     a session ID, or a user name, depending on the environment.
1330    
1331    =over 4
1332    
1333    =item parameter
1334    
1335    Parameter defining the method for finding the tracing key. If it is a scalar,
1336    then it is presumed to be the tracing key itself. If it is a CGI object, then
1337    the tracing key is taken from the C<IP> cookie. Otherwise, the tracing key is
1338    taken from the C<TRACING> environment variable.
1339    
1340    =item RETURN
1341    
1342    Returns the key to be used for labels in emergency tracing.
1343    
1344  =back  =back
1345    
1346  =cut  =cut
1347    
1348  sub StandardSetup {  sub EmergencyKey {
1349      # Get the parameters.      # Get the parameters.
1350      my ($categories, $options, $parmHelp, @argv) = @_;      my ($parameter) = @_;
1351      # Get the default tracing key.      # Declare the return variable.
1352      my $tkey = EmergencyKey();      my $retVal;
1353      # Add the tracing options.      # Determine the parameter type.
1354      if (! exists $options->{trace}) {      if (! defined $parameter || defined($ENV{TRACING})) {
1355          $options->{trace} = ['E', "tracing level (E for emergency tracing)"];          # Here we're supposed to check the environment. If that fails, we
1356      }          # get the effective login ID.
1357      $options->{sql} = [0, "turn on SQL tracing"];          $retVal = $ENV{TRACING} || scalar getpwuid($<);
     $options->{help} = [0, "display command-line options"];  
     $options->{user} = [$tkey, "tracing key"];  
     $options->{background} = [0, "spool standard and error output"];  
     # Create a parsing hash from the options hash. The parsing hash  
     # contains the default values rather than the default value  
     # and the description. While we're at it, we'll memorize the  
     # length of the longest option name.  
     my $longestName = 0;  
     my %parseOptions = ();  
     for my $key (keys %{$options}) {  
         if (length $key > $longestName) {  
             $longestName = length $key;  
         }  
         $parseOptions{$key} = $options->{$key}->[0];  
     }  
     # Parse the command line.  
     my ($retOptions, @retParameters) = ParseCommand(\%parseOptions, @argv);  
     # Get the logfile suffix.  
     my $suffix = $retOptions->{user};  
     # Check for background mode.  
     if ($retOptions->{background}) {  
         my $outFileName = "$FIG_Config::temp/out$suffix.log";  
         my $errFileName = "$FIG_Config::temp/err$suffix.log";  
         open STDOUT, ">$outFileName";  
         open STDERR, ">$errFileName";  
     }  
     # Now we want to set up tracing. First, we need to know if the user  
     # wants emergency tracing.  
     if ($retOptions->{trace} eq 'E') {  
         ETracing($retOptions->{user});  
1358      } else {      } else {
1359          # Here the tracing is controlled from the command line.          my $ptype = ref $parameter;
1360          my @cats = @{$categories};          if ($ptype eq 'CGI') {
1361          if ($retOptions->{sql}) {              # Here we were invoked from a web page. Look for a cookie.
1362              push @cats, "SQL";              $retVal = $parameter->cookie('IP');
1363            } elsif (! $ptype) {
1364                # Here the key was passed in.
1365                $retVal = $parameter;
1366          }          }
         # Add the default categories.  
         push @cats, "Tracer";  
         # Next, we create the category string by joining the categories.  
         my $cats = join(" ", @cats);  
         # Check to determine whether or not the caller wants to turn off tracing  
         # to the standard output.  
         my $traceLevel = $retOptions->{trace};  
         my $textOKFlag = 1;  
         if ($traceLevel =~ /^(.)-/) {  
             $traceLevel = $1;  
             $textOKFlag = 0;  
1367          }          }
1368          # Now we set up the trace mode.      # If no luck finding a key, use the PID.
1369          my $traceMode;      if (! defined $retVal) {
1370          # Verify that we can open a file in the FIG temporary directory.          $retVal = $$;
         my $traceFileName = "$FIG_Config::temp/trace$suffix.log";  
         if (open TESTTRACE, ">$traceFileName") {  
             # Here we can trace to a file.  
             $traceMode = ">$traceFileName";  
             if ($textOKFlag) {  
                 # Echo to standard output if the text-OK flag is set.  
                 $traceMode = "+$traceMode";  
1371              }              }
1372              # Close the test file.      # Return the result.
1373              close TESTTRACE;      return $retVal;
1374          } else {  }
1375              # Here we can't trace to a file. We trace to the standard output if it's  
1376              # okay, and the error log otherwise.  
1377              if ($textOKFlag) {  =head3 TraceParms
1378                  $traceMode = "TEXT";  
1379        Tracer::TraceParms($cgi);
1380    
1381    Trace the CGI parameters at trace level CGI => 3 and the environment variables
1382    at level CGI => 4. A self-referencing URL is traced at level CGI => 2.
1383    
1384    =over 4
1385    
1386    =item cgi
1387    
1388    CGI query object containing the parameters to trace.
1389    
1390    =back
1391    
1392    =cut
1393    
1394    sub TraceParms {
1395        # Get the parameters.
1396        my ($cgi) = @_;
1397        if (T(CGI => 2)) {
1398            # Here we trace the GET-style URL for the script, but only if it's
1399            # relatively small.
1400            my $url = $cgi->url(-relative => 1, -query => 1);
1401            my $len = length($url);
1402            if ($len < 500) {
1403                Trace("[URL] $url");
1404            } elsif ($len > 2048) {
1405                Trace("[URL] URL is too long to use with GET ($len characters).");
1406              } else {              } else {
1407                  $traceMode = "WARN";              Trace("[URL] URL length is $len characters.");
1408              }              }
1409          }          }
1410          # Now set up the tracing.      if (T(CGI => 3)) {
1411          TSetup("$traceLevel $cats", $traceMode);          # Here we want to trace the parameter data.
1412            my @names = $cgi->param;
1413            for my $parmName (sort @names) {
1414                # Note we skip the Trace parameters, which are for our use only.
1415                if ($parmName ne 'Trace' && $parmName ne 'TF') {
1416                    my @values = $cgi->param($parmName);
1417                    Trace("[CGI] $parmName = " . join(", ", @values));
1418      }      }
     # Check for the "h" option. If it is specified, dump the command-line  
     # options and exit the program.  
     if ($retOptions->{help}) {  
         $0 =~ m#[/\\](\w+)(\.pl)?$#i;  
         print "$1 [options] $parmHelp\n";  
         for my $key (sort keys %{$options}) {  
             my $name = Pad($key, $longestName, 0, ' ');  
             my $desc = $options->{$key}->[1];  
             if ($options->{$key}->[0]) {  
                 $desc .= " (default " . $options->{$key}->[0] . ")";  
1419              }              }
1420              print "  $name $desc\n";          # Display the request method.
1421            my $method = $cgi->request_method();
1422            Trace("Method: $method");
1423          }          }
1424          exit(0);      if (T(CGI => 4)) {
1425            # Here we want the environment data too.
1426            for my $envName (sort keys %ENV) {
1427                Trace("[ENV] $envName = $ENV{$envName}");
1428      }      }
     # Trace the options, if applicable.  
     if (T(3)) {  
         my @parms = grep { $retOptions->{$_} } keys %{$retOptions};  
         Trace("Selected options: " . join(", ", sort @parms) . ".");  
1429      }      }
     # Return the parsed parameters.  
     return ($retOptions, @retParameters);  
1430  }  }
1431    
1432  =head3 Setups  =head3 TraceImages
   
 C<< my $count = Tracer::Setups(); >>  
   
 Return the number of times L</TSetup> has been called.  
   
 This method allows for the creation of conditional tracing setups where, for example, we  
 may want to set up tracing if nobody else has done it before us.  
   
 =cut  
   
 sub Setups {  
     return $SetupCount;  
 }  
1433    
1434  =head3 Open      Tracer::TraceImages($htmlString);
1435    
1436  C<< my $handle = Open($fileHandle, $fileSpec, $message); >>  Trace information about all of an html document's images. The tracing
1437    will be for type "IMG" at level 3. The image's source string
1438    will be displayed. This is generally either the URL of the image or
1439    raw data for the image itself. If the source is too long, only the first 300
1440    characters will be shown at trace level 3. The entire source will be shown,
1441    however, at trace level 4. This method is not very smart, and might catch
1442    Javascript code, but it is still useful when debugging the arcane
1443    behavior of images in multiple browser environments.
1444    
1445  Open a file.  =over 4
1446    
1447  The I<$fileSpec> is essentially the second argument of the PERL C<open>  =item htmlString
 function. The mode is specified using Unix-like shell information. So, for  
 example,  
1448    
1449      Open(\*LOGFILE, '>>/usr/spool/news/twitlog', "Could not open twit log.");  HTML text for an outgoing web page.
1450    
1451  would open for output appended to the specified file, and  =back
1452    
1453      Open(\*DATASTREAM, "| sort -u >$outputFile", "Could not open $outputFile.");  =cut
1454    
1455  would open a pipe that sorts the records written and removes duplicates. Note  sub TraceImages {
1456  the use of file handle syntax in the Open call. To use anonymous file handles,      # Only proceed if we're at the proper trace level.
1457  code as follows.      if (T(IMG => 3)) {
1458            # For performance reasons we're manipulating $_[0] instead of retrieving the string
1459            # into a variable called "$htmlString". This is because we expect html strings to be
1460            # long, and don't want to copy them any more than we have to.
1461            Trace(length($_[0]) . " characters in web page.");
1462            # Loop through the HTML, culling image tags.
1463            while ($_[0] =~ /<img\s+[^>]+?src="([^"]+)"/sgi) {
1464                # Extract the source string and determine whether or not it's too long.
1465                my $srcString = $1;
1466                my $pos = pos($_[0]) - length($srcString);
1467                my $excess = length($srcString) - 300;
1468                # We'll put the display string in here.
1469                my $srcDisplay = $srcString;
1470                # If it's a data string, split it at the comma.
1471                $srcDisplay =~ s/^(data[^,]+,)/$1\n/;
1472                # If there's no excess or we're at trace level 4, we're done. At level 3 with
1473                # a long string, however, we only show the first 300 characters.
1474                if ($excess > 0 && ! T(IMG => 4)) {
1475                    $srcDisplay = substr($srcDisplay,0,300) . "\nplus $excess characters.";
1476                }
1477                # Output the trace message.
1478                Trace("Image tag at position $pos:\n$srcDisplay");
1479            }
1480        }
1481    }
1482    
1483      my $logFile = Open(undef, '>>/usr/spool/news/twitlog', "Could not open twit log.");  =head2 Command-Line Utility Methods
1484    
1485  The I<$message> parameter is used if the open fails. If it is set to C<0>, then  =head3 SendSMS
 the open returns TRUE if successful and FALSE if an error occurred. Otherwise, a  
 failed open will throw an exception and the third parameter will be used to construct  
 an error message. If the parameter is omitted, a standard message is constructed  
 using the file spec.  
1486    
1487      Could not open "/usr/spool/news/twitlog"      my $msgID = Tracer::SendSMS($phoneNumber, $msg);
1488    
1489  Note that the mode characters are automatically cleaned from the file name.  Send a text message to a phone number using Clickatell. The FIG_Config file must contain the
1490  The actual error message from the file system will be captured and appended to the  user name, password, and API ID for the relevant account in the hash reference variable
1491  message in any case.  I<$FIG_Config::phone>, using the keys C<user>, C<password>, and C<api_id>. For
1492    example, if the user name is C<BruceTheHumanPet>, the password is C<silly>, and the API ID
1493    is C<2561022>, then the FIG_Config file must contain
1494    
1495      Could not open "/usr/spool/news/twitlog": file not found.      $phone =  { user => 'BruceTheHumanPet',
1496                    password => 'silly',
1497                    api_id => '2561022' };
1498    
1499  In some versions of PERL the only error message we get is a number, which  The original purpose of this method was to insure Bruce would be notified immediately when the
1500  corresponds to the C++ C<errno> value.  Sprout Load terminates. Care should be taken if you do not wish Bruce to be notified immediately
1501    when you call this method.
1502    
1503      Could not open "/usr/spool/news/twitlog": 6.  The message ID will be returned if successful, and C<undef> if an error occurs.
1504    
1505  =over 4  =over 4
1506    
1507  =item fileHandle  =item phoneNumber
   
 File handle. If this parameter is C<undef>, a file handle will be generated  
 and returned as the value of this method.  
   
 =item fileSpec  
1508    
1509  File name and mode, as per the PERL C<open> function.  Phone number to receive the message, in international format. A United States phone number
1510    would be prefixed by "1". A British phone number would be prefixed by "44".
1511    
1512  =item message (optional)  =item msg
1513    
1514  Error message to use if the open fails. If omitted, a standard error message  Message to send to the specified phone.
 will be generated. In either case, the error information from the file system  
 is appended to the message. To specify a conditional open that does not throw  
 an error if it fails, use C<0>.  
1515    
1516  =item RETURN  =item RETURN
1517    
1518  Returns the name of the file handle assigned to the file, or C<undef> if the  Returns the message ID if successful, and C<undef> if the message could not be sent.
 open failed.  
1519    
1520  =back  =back
1521    
1522  =cut  =cut
1523    
1524  sub Open {  sub SendSMS {
1525      # Get the parameters.      # Get the parameters.
1526      my ($fileHandle, $fileSpec, $message) = @_;      my ($phoneNumber, $msg) = @_;
1527      # Attempt to open the file.      # Declare the return variable. If we do not change it, C<undef> will be returned.
1528      my $rv = open $fileHandle, $fileSpec;      my $retVal;
1529      # If the open failed, generate an error message.      # Only proceed if we have phone support.
1530      if (! $rv) {      if (! defined $FIG_Config::phone) {
1531          # Save the system error message.          Trace("Phone support not present in FIG_Config.") if T(1);
1532          my $sysMessage = $!;      } else {
1533          # See if we need a default message.          # Get the phone data.
1534          if (!$message) {          my $parms = $FIG_Config::phone;
1535              # Clean any obvious mode characters and leading spaces from the          # Get the Clickatell URL.
1536              # filename.          my $url = "http://api.clickatell.com/http/";
1537              my ($fileName) = FindNamePart($fileSpec);          # Create the user agent.
1538              $message = "Could not open \"$fileName\"";          my $ua = LWP::UserAgent->new;
1539            # Request a Clickatell session.
1540            my $resp = $ua->post("$url/sendmsg", { user => $parms->{user},
1541                                         password => $parms->{password},
1542                                         api_id => $parms->{api_id},
1543                                         to => $phoneNumber,
1544                                         text => $msg});
1545            # Check for an error.
1546            if (! $resp->is_success) {
1547                Trace("Alert failed.") if T(1);
1548            } else {
1549                # Get the message ID.
1550                my $rstring = $resp->content;
1551                if ($rstring =~ /^ID:\s+(.*)$/) {
1552                    $retVal = $1;
1553                } else {
1554                    Trace("Phone attempt failed with $rstring") if T(1);
1555          }          }
         # Terminate with an error using the supplied message and the  
         # error message from the file system.  
         Confess("$message: $!");  
1556      }      }
1557      # Return the file handle.      }
1558      return $fileHandle;      # Return the result.
1559        return $retVal;
1560  }  }
1561    
1562  =head3 FindNamePart  =head3 StandardSetup
1563    
1564  C<< my ($fileName, $start, $len) = Tracer::FindNamePart($fileSpec); >>      my ($options, @parameters) = StandardSetup(\@categories, \%options, $parmHelp, @ARGV);
1565    
1566  Extract the portion of a file specification that contains the file name.  This method performs standard command-line parsing and tracing setup. The return
1567    values are a hash of the command-line options and a list of the positional
1568    parameters. Tracing is automatically set up and the command-line options are
1569    validated.
1570    
1571  A file specification is the string passed to an C<open> call. It specifies the file  This is a complex method that does a lot of grunt work. The parameters can
1572  mode and name. In a truly complex situation, it can specify a pipe sequence. This  be more easily understood, however, once they are examined individually.
 method assumes that the file name is whatever follows the first angle bracket  
 sequence.  So, for example, in the following strings the file name is  
 C</usr/fig/myfile.txt>.  
1573    
1574      >>/usr/fig/myfile.txt  The I<categories> parameter is the most obtuse. It is a reference to a list of
1575      </usr/fig/myfile.txt  special-purpose tracing categories. Most tracing categories are PERL package
1576      | sort -u > /usr/fig/myfile.txt  names. So, for example, if you wanted to turn on tracing inside the B<Sprout>,
1577    B<ERDB>, and B<SproutLoad> packages, you would specify the categories
1578    
1579  If the method cannot find a file name using its normal methods, it will return the      ["Sprout", "SproutLoad", "ERDB"]
1580  whole incoming string.  
1581    This would cause trace messages in the specified three packages to appear in
1582    the output. There are two special tracing categories that are automatically
1583    handled by this method. In other words, if you used L</TSetup> you would need
1584    to include these categories manually, but if you use this method they are turned
1585    on automatically.
1586    
1587  =over 4  =over 4
1588    
1589  =item fileSpec  =item SQL
1590    
1591  File specification string from which the file name is to be extracted.  Traces SQL commands and activity.
1592    
1593  =item RETURN  =item Tracer
1594    
1595  Returns a three-element list. The first element contains the file name portion of  Traces error messages and call stacks.
 the specified string, or the whole string if a file name cannot be found via normal  
 methods. The second element contains the start position of the file name portion and  
 the third element contains the length.  
1596    
1597  =back  =back
1598    
1599  =cut  C<SQL> is only turned on if the C<-sql> option is specified in the command line.
1600  #: Return Type $;  The trace level is specified using the C<-trace> command-line option. For example,
1601  sub FindNamePart {  the following command line for C<TransactFeatures> turns on SQL tracing and runs
1602      # Get the parameters.  all tracing at level 3.
     my ($fileSpec) = @_;  
     # Default to the whole input string.  
     my ($retVal, $pos, $len) = ($fileSpec, 0, length $fileSpec);  
     # Parse out the file name if we can.  
     if ($fileSpec =~ m/(<|>>?)(.+?)(\s*)$/) {  
         $retVal = $2;  
         $len = length $retVal;  
         $pos = (length $fileSpec) - (length $3) - $len;  
     }  
     # Return the result.  
     return ($retVal, $pos, $len);  
 }  
   
 =head3 OpenDir  
   
 C<< my @files = OpenDir($dirName, $filtered, $flag); >>  
1603    
1604  Open a directory and return all the file names. This function essentially performs      TransactFeatures -trace=3 -sql register ../xacts IDs.tbl
 the functions of an C<opendir> and C<readdir>. If the I<$filtered> parameter is  
 set to TRUE, all filenames beginning with a period (C<.>), dollar sign (C<$>),  
 or pound sign (C<#>) and all filenames ending with a tilde C<~>) will be  
 filtered out of the return list. If the directory does not open and I<$flag> is not  
 set, an exception is thrown. So, for example,  
1605    
1606      my @files = OpenDir("/Volumes/fig/contigs", 1);  Standard tracing is output to the standard output and echoed to the file
1607    C<trace>I<$$>C<.log> in the FIG temporary directory, where I<$$> is the
1608    process ID. You can also specify the C<user> parameter to put a user ID
1609    instead of a process ID in the trace file name. So, for example
1610    
1611  is effectively the same as  The default trace level is 2. To get all messages, specify a trace level of 4.
1612    For a genome-by-genome update, use 3.
1613    
1614      opendir(TMP, "/Volumes/fig/contigs") || Confess("Could not open /Volumes/fig/contigs.");      TransactFeatures -trace=3 -sql -user=Bruce register ../xacts IDs.tbl
     my @files = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir(TMP);  
1615    
1616  Similarly, the following code  would send the trace output to C<traceBruce.log> in the temporary directory.
1617    
1618      my @files = grep { $_ =~ /^\d/ } OpenDir("/Volumes/fig/orgs", 0, 1);  The I<options> parameter is a reference to a hash containing the command-line
1619    options, their default values, and an explanation of what they mean. Command-line
1620    options may be in the form of switches or keywords. In the case of a switch, the
1621    option value is 1 if it is specified and 0 if it is not specified. In the case
1622    of a keyword, the value is separated from the option name by an equal sign. You
1623    can see this last in the command-line example above.
1624    
1625  Returns the names of all files in C</Volumes/fig/orgs> that begin with digits and  You can specify a different default trace level by setting C<$options->{trace}>
1626  automatically returns an empty list if the directory fails to open.  prior to calling this method.
1627    
1628  =over 4  An example at this point would help. Consider, for example, the command-line utility
1629    C<TransactFeatures>. It accepts a list of positional parameters plus the options
1630    C<safe>, C<noAlias>, C<start>, and C<tblFiles>. To start up this command, we execute
1631    the following code.
1632    
1633  =item dirName      my ($options, @parameters) = Tracer::StandardSetup(["DocUtils"],
1634                            { safe => [0, "use database transactions"],
1635                              noAlias => [0, "do not expect aliases in CHANGE transactions"],
1636                              start => [' ', "start with this genome"],
1637                              tblFiles => [0, "output TBL files containing the corrected IDs"] },
1638                            "<command> <transactionDirectory> <IDfile>",
1639                          @ARGV);
1640    
 Name of the directory to open.  
1641    
1642  =item filtered  The call to C<ParseCommand> specifies the default values for the options and
1643    stores the actual options in a hash that is returned as C<$options>. The
1644    positional parameters are returned in C<@parameters>.
1645    
1646  TRUE if files whose names begin with a period (C<.>) should be automatically removed  The following is a sample command line for C<TransactFeatures>.
 from the list, else FALSE.  
1647    
1648  =item flag      TransactFeatures -trace=2 -noAlias register ../xacts IDs.tbl
1649    
1650  TRUE if a failure to open is okay, else FALSE  Single and double hyphens are equivalent. So, you could also code the
1651    above command as
1652    
1653  =back      TransactFeatures --trace=2 --noAlias register ../xacts IDs.tbl
1654    
1655  =cut  In this case, C<register>, C<../xacts>, and C<IDs.tbl> are the positional
1656  #: Return Type @;  parameters, and would find themselves in I<@parameters> after executing the
1657  sub OpenDir {  above code fragment. The tracing would be set to level 2, and the categories
1658      # Get the parameters.  would be C<Tracer>, and <DocUtils>. C<Tracer> is standard,
1659      my ($dirName, $filtered, $flag) = @_;  and C<DocUtils> was included because it came in within the first parameter
1660      # Declare the return variable.  to this method. The I<$options> hash would be
     my @retVal = ();  
     # Open the directory.  
     if (opendir(my $dirHandle, $dirName)) {  
         # The directory opened successfully. Get the appropriate list according to the  
         # strictures of the filter parameter.  
         if ($filtered) {  
             @retVal = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir $dirHandle;  
         } else {  
             @retVal = readdir $dirHandle;  
         }  
     } elsif (! $flag) {  
         # Here the directory would not open and it's considered an error.  
         Confess("Could not open directory $dirName.");  
     }  
     # Return the result.  
     return @retVal;  
 }  
1661    
1662  =head3 SetLevel      { trace => 2, sql => 0, safe => 0,
1663          noAlias => 1, start => ' ', tblFiles => 0 }
1664    
1665  C<< Tracer::SetLevel($newLevel); >>  Use of C<StandardSetup> in this way provides a simple way of performing
1666    standard tracing setup and command-line parsing. Note that the caller is
1667    not even aware of the command-line switches C<-trace> and C<-sql>, which
1668    are used by this method to control the tracing. If additional tracing features
1669    need to be added in the future, they can be processed by this method without
1670    upsetting the command-line utilities.
1671    
1672  Modify the trace level. A higher trace level will cause more messages to appear.  If the C<background> option is specified on the command line, then the
1673    standard and error outputs will be directed to files in the temporary
1674    directory, using the same suffix as the trace file. So, if the command
1675    line specified
1676    
1677  =over 4      -user=Bruce -background
1678    
1679  =item newLevel  then the trace output would go to C<traceBruce.log>, the standard output to
1680    C<outBruce.log>, and the error output to C<errBruce.log>. This is designed to
1681    simplify starting a command in the background.
1682    
1683  Proposed new trace level.  The user name is also used as the tracing key for L</Emergency Tracing>.
1684    Specifying a value of C<E> for the trace level causes emergency tracing to
1685    be used instead of custom tracing. If the user name is not specified,
1686    the tracing key is taken from the C<Tracing> environment variable. If there
1687    is no value for that variable, the tracing key will be computed from the active
1688    login ID.
1689    
1690  =back  Since the default situation in StandardSetup is to trace to the standard
1691    output, errors that occur in command-line scripts will not generate
1692    RSS events. To force the events, use the C<warn> option.
1693    
1694  =cut      TransactFeatures -background -warn register ../xacts IDs.tbl
1695    
1696  sub SetLevel {  Finally, if the special option C<-help> is specified, the option
1697      $TraceLevel = $_[0];  names will be traced at level 0 and the program will exit without processing.
1698  }  This provides a limited help capability. For example, if the user enters
1699    
1700  =head3 Now      TransactFeatures -help
1701    
1702  C<< my $string = Tracer::Now(); >>  he would see the following output.
1703    
1704  Return a displayable time stamp containing the local time.      TransactFeatures [options] <command> <transactionDirectory> <IDfile>
1705            -trace    tracing level (default E)
1706            -sql      trace SQL commands
1707            -safe     use database transactions
1708            -noAlias  do not expect aliases in CHANGE transactions
1709            -start    start with this genome
1710            -tblFiles output TBL files containing the corrected IDs
1711            -forked   do not erase the trace file before tracing
1712    
1713  =cut  The caller has the option of modifying the tracing scheme by placing a value
1714    for C<trace> in the incoming options hash. The default value can be overridden,
1715    or the tracing to the standard output can be turned off by suffixing a minus
1716    sign to the trace level. So, for example,
1717    
1718  sub Now {      { trace => [0, "tracing level (default 0)"],
1719      my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);         ...
     my $retVal = _p2($mon+1) . "/" . _p2($mday) . "/" . ($year + 1900) . " " .  
                  _p2($hour) . ":" . _p2($min) . ":" . _p2($sec);  
     return $retVal;  
 }  
1720    
1721  # Pad a number to 2 digits.  would set the default trace level to 0 instead of E, while
 sub _p2 {  
     my ($value) = @_;  
     $value = "0$value" if ($value < 10);  
     return $value;  
 }  
1722    
1723  =head3 ParseTraceDate      { trace => ["2-", "tracing level (default 2)"],
1724           ...
1725    
1726  C<< my $time = Tracer::ParseTraceDate($dateString); >>  would set the default to 2, but trace only to the log file, not to the
1727    standard output.
1728    
1729  Convert a date from the trace file into a PERL timestamp.  The parameters to this method are as follows.
1730    
1731  =over 4  =over 4
1732    
1733  =item dateString  =item categories
   
 The date string from the trace file. The format of the string is determined by the  
 L</Now> method.  
   
 =item RETURN  
   
 Returns a PERL time, that is, a number of seconds since the epoch, or C<undef> if  
 the time string is invalid.  
1734    
1735  =back  Reference to a list of tracing category names. These should be names of
1736    packages whose internal workings will need to be debugged to get the
1737    command working.
1738    
1739  =cut  =item options
1740    
1741  sub ParseTraceDate {  Reference to a hash containing the legal options for the current command mapped
1742      # Get the parameters.  to their default values and descriptions. The user can override the defaults
1743      my ($dateString) = @_;  by specifying the options as command-line switches prefixed by a hyphen.
1744      # Declare the return variable.  Tracing-related options may be added to this hash. If the C<-h> option is
1745      my $retVal;  specified on the command line, the option descriptions will be used to
1746      # Parse the date.  explain the options. To turn off tracing to the standard output, add a
1747      if ($dateString =~ m#(\d+)/(\d+)/(\d+)\s+(\d+):(\d+):(\d+)#) {  minus sign to the value for C<trace> (see above).
         # Create a time object. Note we need to convert the day, month,  
         # and year to a different base. Years count from 1900, and  
         # the internal month value is relocated to January = 0.  
         $retVal = timelocal($6, $5, $4, $2, $1 - 1, $3 - 1900);  
     }  
     # Return the result.  
     return $retVal;  
 }  
1748    
1749  =head3 LogErrors  =item parmHelp
1750    
1751  C<< Tracer::LogErrors($fileName); >>  A string that vaguely describes the positional parameters. This is used
1752    if the user specifies the C<-h> option.
1753    
1754  Route the standard error output to a log file.  =item argv
1755    
1756  =over 4  List of command line parameters, including the option switches, which must
1757    precede the positional parameters and be prefixed by a hyphen.
1758    
1759  =item fileName  =item RETURN
1760    
1761  Name of the file to receive the error output.  Returns a list. The first element of the list is the reference to a hash that
1762    maps the command-line option switches to their values. These will either be the
1763    default values or overrides specified on the command line. The remaining
1764    elements of the list are the position parameters, in order.
1765    
1766  =back  =back
1767    
1768  =cut  =cut
1769    
1770  sub LogErrors {  sub StandardSetup {
1771      # Get the file name.      # Get the parameters.
1772      my ($fileName) = @_;      my ($categories, $options, $parmHelp, @argv) = @_;
1773      # Open the file as the standard error output.      # Get the default tracing key.
1774      open STDERR, '>', $fileName;      my $tkey = EmergencyKey();
1775        # Save the command line.
1776        $CommandLine = join(" ", $0, map { $_ =~ /\s/ ? "\"$_\"" : $_ } @argv);
1777        # Add the tracing options.
1778        if (! exists $options->{trace}) {
1779            $options->{trace} = ['2', "tracing level (E for emergency tracing)"];
1780        }
1781        if (! exists $options->{forked}) {
1782            $options->{forked} = [0, "keep old trace file"];
1783        }
1784        $options->{sql} = [0, "turn on SQL tracing"];
1785        $options->{help} = [0, "display command-line options"];
1786        $options->{user} = [$tkey, "tracing key"];
1787        $options->{background} = [0, "spool standard and error output"];
1788        $options->{warn} = [0, "send errors to RSS feed"];
1789        $options->{moreTracing} = ["", "comma-delimited list of additional trace modules for debugging"];
1790        # Create a parsing hash from the options hash. The parsing hash
1791        # contains the default values rather than the default value
1792        # and the description. While we're at it, we'll memorize the
1793        # length of the longest option name.
1794        my $longestName = 0;
1795        my %parseOptions = ();
1796        for my $key (keys %{$options}) {
1797            if (length $key > $longestName) {
1798                $longestName = length $key;
1799            }
1800            $parseOptions{$key} = $options->{$key}->[0];
1801        }
1802        # Parse the command line.
1803        my ($retOptions, @retParameters) = ParseCommand(\%parseOptions, @argv);
1804        # Get the logfile suffix.
1805        my $suffix = $retOptions->{user};
1806        # We'll put the trace file name in here. We need it later if background
1807        # mode is on.
1808        my $traceFileName;
1809        # Now we want to set up tracing. First, we need to know if the user
1810        # wants emergency tracing.
1811        if ($retOptions->{trace} eq 'E') {
1812            ETracing($retOptions->{user});
1813        } else {
1814            # Here the tracing is controlled from the command line.
1815            my @cats = @{$categories};
1816            if ($retOptions->{sql}) {
1817                push @cats, "SQL";
1818            }
1819            if ($retOptions->{warn}) {
1820                push @cats, "Feed";
1821            }
1822            # Add the default categories.
1823            push @cats, "Tracer";
1824            # Check for more tracing groups.
1825            if ($retOptions->{moreTracing}) {
1826                push @cats, split /,/, $retOptions->{moreTracing};
1827            }
1828            # Next, we create the category string by joining the categories.
1829            my $cats = join(" ", @cats);
1830            # Check to determine whether or not the caller wants to turn off tracing
1831            # to the standard output.
1832            my $traceLevel = $retOptions->{trace};
1833            my $textOKFlag = 1;
1834            if ($traceLevel =~ /^(.)-/) {
1835                $traceLevel = $1;
1836                $textOKFlag = 0;
1837            }
1838            # Now we set up the trace mode.
1839            my $traceMode;
1840            # Verify that we can open a file in the FIG temporary directory.
1841            my $traceFileName = "$FIG_Config::temp/trace$suffix.log";
1842            my $traceFileSpec = ($retOptions->{forked} ? ">>$traceFileName" : ">$traceFileName");
1843            if (open TESTTRACE, "$traceFileSpec") {
1844                # Here we can trace to a file.
1845                $traceMode = ">>$traceFileName";
1846                if ($textOKFlag) {
1847                    # Echo to standard output if the text-OK flag is set.
1848                    $traceMode = "+$traceMode";
1849                }
1850                # Close the test file.
1851                close TESTTRACE;
1852            } else {
1853                # Here we can't trace to a file. Complain about this.
1854                warn "Could not open trace file $traceFileName: $!\n";
1855                # We trace to the standard output if it's
1856                # okay, and the error log otherwise.
1857                if ($textOKFlag) {
1858                    $traceMode = "TEXT";
1859                } else {
1860                    $traceMode = "WARN";
1861                }
1862            }
1863            # Now set up the tracing.
1864            TSetup("$traceLevel $cats", $traceMode);
1865        }
1866        # Check for background mode.
1867        if ($retOptions->{background}) {
1868            my $outFileName = "$FIG_Config::temp/out$suffix$$.log";
1869            my $errFileName = "$FIG_Config::temp/err$suffix$$.log";
1870            # Spool the output.
1871            open STDOUT, ">$outFileName";
1872            # If we have a trace file, trace the errors to the log. Otherwise,
1873            # spool the errors.
1874            if (defined $traceFileName) {
1875                open STDERR, "| Tracer $traceFileName";
1876            } else {
1877                open STDERR, ">$errFileName";
1878            }
1879            # Check for phone support. If we have phone support and a phone number,
1880            # we want to turn it on.
1881            if ($ENV{PHONE} && defined($FIG_Config::phone)) {
1882                $retOptions->{phone} = $ENV{PHONE};
1883            }
1884        }
1885        # Check for the "help" option. If it is specified, dump the command-line
1886        # options and exit the program.
1887        if ($retOptions->{help}) {
1888            $0 =~ m#[/\\](\w+)(\.pl)?$#i;
1889            print "$1 [options] $parmHelp\n";
1890            for my $key (sort keys %{$options}) {
1891                my $name = Pad($key, $longestName, 0, ' ');
1892                my $desc = $options->{$key}->[1];
1893                if ($options->{$key}->[0]) {
1894                    $desc .= " (default " . $options->{$key}->[0] . ")";
1895                }
1896                print "  $name $desc\n";
1897            }
1898            exit(0);
1899        }
1900        # Trace the options, if applicable.
1901        if (T(3)) {
1902            my @parms = grep { $retOptions->{$_} } keys %{$retOptions};
1903            Trace("Selected options: " . join(", ", sort @parms) . ".");
1904        }
1905        # Return the parsed parameters.
1906        return ($retOptions, @retParameters);
1907  }  }
1908    
1909  =head3 ReadOptions  =head3 ReadOptions
1910    
1911  C<< my %options = Tracer::ReadOptions($fileName); >>      my %options = Tracer::ReadOptions($fileName);
1912    
1913  Read a set of options from a file. Each option is encoded in a line of text that has the  Read a set of options from a file. Each option is encoded in a line of text that has the
1914  format  format
# Line 1069  Line 1969 
1969    
1970  =head3 GetOptions  =head3 GetOptions
1971    
1972  C<< Tracer::GetOptions(\%defaults, \%options); >>      Tracer::GetOptions(\%defaults, \%options);
1973    
1974  Merge a specified set of options into a table of defaults. This method takes two hash references  Merge a specified set of options into a table of defaults. This method takes two hash references
1975  as input and uses the data from the second to update the first. If the second does not exist,  as input and uses the data from the second to update the first. If the second does not exist,
# Line 1078  Line 1978 
1978    
1979  Consider the following example.  Consider the following example.
1980    
1981  C<< my $optionTable = GetOptions({ dbType => 'mySQL', trace => 0 }, $options); >>      my $optionTable = GetOptions({ dbType => 'mySQL', trace => 0 }, $options);
1982    
1983  In this example, the variable B<$options> is expected to contain at most two options-- B<dbType> and  In this example, the variable B<$options> is expected to contain at most two options-- B<dbType> and
1984  B<trace>. The default database type is C<mySQL> and the default trace level is C<0>. If the value of  B<trace>. The default database type is C<mySQL> and the default trace level is C<0>. If the value of
# Line 1086  Line 1986 
1986  the trace level will remain at 0. If B<$options> is undefined, then the database type and trace level  the trace level will remain at 0. If B<$options> is undefined, then the database type and trace level
1987  will remain C<mySQL> and C<0>. If, on the other hand, B<$options> is defined as  will remain C<mySQL> and C<0>. If, on the other hand, B<$options> is defined as
1988    
1989  C<< {databaseType => 'Oracle'} >>      {databaseType => 'Oracle'}
1990    
1991  an error will occur because the B<databaseType> option does not exist.  an error will occur because the B<databaseType> option does not exist.
1992    
# Line 1130  Line 2030 
2030    
2031  =head3 MergeOptions  =head3 MergeOptions
2032    
2033  C<< Tracer::MergeOptions(\%table, \%defaults); >>      Tracer::MergeOptions(\%table, \%defaults);
2034    
2035  Merge default values into a hash table. This method looks at the key-value pairs in the  Merge default values into a hash table. This method looks at the key-value pairs in the
2036  second (default) hash, and if a matching key is not found in the first hash, the default  second (default) hash, and if a matching key is not found in the first hash, the default
# Line 1162  Line 2062 
2062      }      }
2063  }  }
2064    
2065  =head3 Trace  =head3 UnparseOptions
   
 C<< Trace($message); >>  
   
 Write a trace message to the target location specified in L</TSetup>. If there has not been  
 any prior call to B<TSetup>.  
   
 =over 4  
   
 =item message  
   
 Message to write.  
   
 =back  
   
 =cut  
   
 sub Trace {  
     # Get the parameters.  
     my ($message) = @_;  
     # Get the timestamp.  
     my $timeStamp = Now();  
     # Format the message. Note we strip off any line terminators at the end.  
     my $formatted = "[$timeStamp] <$LastCategory>: " . Strip($message);  
     # Process according to the destination.  
     if ($Destination eq "TEXT") {  
         # Write the message to the standard output.  
         print "$formatted\n";  
     } elsif ($Destination eq "ERROR") {  
         # Write the message to the error output.  
         print STDERR "$formatted\n";  
     } elsif ($Destination eq "QUEUE") {  
         # Push the message into the queue.  
         push @Queue, "$formatted";  
     } elsif ($Destination eq "HTML") {  
         # Convert the message to HTML and write it to the standard output.  
         my $escapedMessage = CGI::escapeHTML($message);  
         print "<p>$formatted</p>\n";  
     } elsif ($Destination eq "WARN") {  
        # Emit the message as a warning.  
        warn $message;  
     } elsif ($Destination =~ m/^>>/) {  
         # Write the trace message to an output file.  
         (open TRACING, $Destination) || die "Tracing open for \"$Destination\" failed: $!";  
         print TRACING "$formatted\n";  
         close TRACING;  
         # If the Tee flag is on, echo it to the standard output.  
         if ($TeeFlag) {  
             print "$formatted\n";  
         }  
     }  
 }  
   
 =head3 T  
   
 C<< my $switch = T($category, $traceLevel); >>  
   
     or  
2066    
2067  C<< my $switch = T($traceLevel); >>      my $optionString = Tracer::UnparseOptions(\%options);
2068    
2069  Return TRUE if the trace level is at or above a specified value and the specified category  Convert an option hash into a command-line string. This will not
2070  is active, else FALSE. If no category is specified, the caller's package name is used.  necessarily be the same text that came in, but it will nonetheless
2071    produce the same ultimate result when parsed by L</StandardSetup>.
2072    
2073  =over 4  =over 4
2074    
2075  =item category  =item options
   
 Category to which the message belongs. If not specified, the caller's package name is  
 used.  
   
 =item traceLevel  
2076    
2077  Relevant tracing level.  Reference to a hash of options to convert into an option string.
2078    
2079  =item RETURN  =item RETURN
2080    
2081  TRUE if a message at the specified trace level would appear in the trace, else FALSE.  Returns a string that will parse to the same set of options when
2082    parsed by L</StandardSetup>.
2083    
2084  =back  =back
2085    
2086  =cut  =cut
2087    
2088  sub T {  sub UnparseOptions {
     # Declare the return variable.  
     my $retVal = 0;  
     # Only proceed if tracing is turned on.  
     if ($Destination ne "NONE") {  
2089          # Get the parameters.          # Get the parameters.
2090          my ($category, $traceLevel) = @_;      my ($options) = @_;
2091          if (!defined $traceLevel) {      # The option segments will be put in here.
2092              # Here we have no category, so we need to get the calling package.      my @retVal = ();
2093              # The calling package is normally the first parameter. If it is      # Loop through the options.
2094              # omitted, the first parameter will be the tracelevel. So, the      for my $key (keys %$options) {
2095              # first thing we do is shift the so-called category into the          # Get the option value.
2096              # $traceLevel variable where it belongs.          my $value = $options->{$key};
2097              $traceLevel = $category;          # Only use it if it's nonempty.
2098              my ($package, $fileName, $line) = caller;          if (defined $value && $value ne "") {
2099              # If there is no calling package, we default to "main".              my $segment = "--$key=$value";
2100              if (!$package) {              # Quote it if necessary.
2101                  $category = "main";              if ($segment =~ /[ |<>*]/) {
2102              } else {                  $segment = '"' . $segment . '"';
                 $category = $package;  
             }  
2103          }          }
2104          # Save the category name.              # Add it to the return list.
2105          $LastCategory = $category;              push @retVal, $segment;
         # Convert it to lower case before we hash it.  
         $category = lc $category;  
         # Use the category and tracelevel to compute the result.  
         if (ref $traceLevel) {  
             Confess("Bad trace level.");  
         } elsif (ref $TraceLevel) {  
             Confess("Bad trace config.");  
2106          }          }
         $retVal = ($traceLevel <= $TraceLevel && ($AllTrace || exists $Categories{$category}));  
2107      }      }
2108      # Return the computed result.      # Return the result.
2109      return $retVal;      return join(" ", @retVal);
2110  }  }
2111    
2112  =head3 ParseCommand  =head3 ParseCommand
2113    
2114  C<< my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList); >>      my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList);
2115    
2116  Parse a command line consisting of a list of parameters. The initial parameters may be option  Parse a command line consisting of a list of parameters. The initial parameters may be option
2117  specifiers of the form C<->I<option> or C<->I<option>C<=>I<value>. The options are stripped  specifiers of the form C<->I<option> or C<->I<option>C<=>I<value>. The options are stripped
2118  off and merged into a table of default options. The remainder of the command line is  off and merged into a table of default options. The remainder of the command line is
2119  returned as a list of positional arguments. For example, consider the following invocation.  returned as a list of positional arguments. For example, consider the following invocation.
2120    
2121  C<< my ($options, @arguments) = ParseCommand({ errors => 0, logFile => 'trace.log'}, @words); >>      my ($options, @arguments) = ParseCommand({ errors => 0, logFile => 'trace.log'}, @words);
2122    
2123  In this case, the list @words will be treated as a command line and there are two options available,  In this case, the list @words will be treated as a command line and there are two options available,
2124  B<errors> and B<logFile>. If @words has the following format  B<errors> and B<logFile>. If @words has the following format
2125    
2126  C<< -logFile=error.log apple orange rutabaga >>      -logFile=error.log apple orange rutabaga
2127    
2128  then at the end of the invocation, C<$options> will be  then at the end of the invocation, C<$options> will be
2129    
2130  C<< { errors => 0, logFile => 'error.log' } >>      { errors => 0, logFile => 'error.log' }
2131    
2132  and C<@arguments> will contain  and C<@arguments> will contain
2133    
2134  C<< apple orange rutabaga >>      apple orange rutabaga
2135    
2136  The parser allows for some escape sequences. See L</UnEscape> for a description. There is no  The parser allows for some escape sequences. See L</UnEscape> for a description. There is no
2137  support for quote characters. Options can be specified with single or double hyphens.  support for quote characters. Options can be specified with single or double hyphens.
# Line 1359  Line 2185 
2185      return ($optionTable, @retVal);      return ($optionTable, @retVal);
2186  }  }
2187    
 =head3 Escape  
2188    
2189  C<< my $codedString = Tracer::Escape($realString); >>  =head2 File Utility Methods
2190    
2191  Escape a string for use in a command length. Tabs will be replaced by C<\t>, new-lines  =head3 GetFile
2192  replaced by C<\n>, carriage returns will be deleted, and backslashes will be doubled. The  
2193  result is to reverse the effect of L</UnEscape>.      my @fileContents = Tracer::GetFile($fileName);
2194    
2195        or
2196    
2197        my $fileContents = Tracer::GetFile($fileName);
2198    
2199    Return the entire contents of a file. In list context, line-ends are removed and
2200    each line is a list element. In scalar context, line-ends are replaced by C<\n>.
2201    
2202  =over 4  =over 4
2203    
2204  =item realString  =item fileName
2205    
2206  String to escape.  Name of the file to read.
2207    
2208  =item RETURN  =item RETURN
2209    
2210  Escaped equivalent of the real string.  In a list context, returns the entire file as a list with the line terminators removed.
2211    In a scalar context, returns the entire file as a string. If an error occurs opening
2212    the file, an empty list will be returned.
2213    
2214  =back  =back
2215    
2216  =cut  =cut
2217    
2218  sub Escape {  sub GetFile {
2219      # Get the parameter.      # Get the parameters.
2220      my ($realString) = @_;      my ($fileName) = @_;
2221      # Initialize the return variable.      # Declare the return variable.
2222      my $retVal = "";      my @retVal = ();
2223      # Loop through the parameter string, looking for sequences to escape.      # Open the file for input.
2224      while (length $realString > 0) {      my $handle = Open(undef, "<$fileName");
2225          # Look for the first sequence to escape.      # Read the whole file into the return variable, stripping off any terminator
2226          if ($realString =~ /^(.*?)([\n\t\r\\])/) {      # characters.
2227              # Here we found it. The text preceding the sequence is in $1. The sequence      my $lineCount = 0;
2228              # itself is in $2. First, move the clear text to the return variable.      while (my $line = <$handle>) {
2229              $retVal .= $1;          $lineCount++;
2230              # Strip the processed section off the real string.          $line = Strip($line);
2231              $realString = substr $realString, (length $2) + (length $1);          push @retVal, $line;
             # Get the matched character.  
             my $char = $2;  
             # If we have a CR, we are done.  
             if ($char ne "\r") {  
                 # It's not a CR, so encode the escape sequence.  
                 $char =~ tr/\t\n/tn/;  
                 $retVal .= "\\" . $char;  
2232              }              }
2233        # Close it.
2234        close $handle;
2235        my $actualLines = @retVal;
2236        Trace("$actualLines lines read from file $fileName.") if T(File => 2);
2237        # Return the file's contents in the desired format.
2238        if (wantarray) {
2239            return @retVal;
2240          } else {          } else {
2241              # Here there are no more escape sequences. The rest of the string is          return join "\n", @retVal;
             # transferred unmodified.  
             $retVal .= $realString;  
             $realString = "";  
         }  
2242      }      }
     # Return the result.  
     return $retVal;  
2243  }  }
2244    
2245  =head3 UnEscape  =head3 PutFile
2246    
2247  C<< my $realString = Tracer::UnEscape($codedString); >>      Tracer::PutFile($fileName, \@lines);
2248    
2249  Replace escape sequences with their actual equivalents. C<\t> will be replaced by  Write out a file from a list of lines of text.
 a tab, C<\n> by a new-line character, and C<\\> by a backslash. C<\r> codes will  
 be deleted.  
2250    
2251  =over 4  =over 4
2252    
2253  =item codedString  =item fileName
2254    
2255  String to un-escape.  Name of the output file.
2256    
2257  =item RETURN  =item lines
2258    
2259  Returns a copy of the original string with the escape sequences converted to their actual  Reference to a list of text lines. The lines will be written to the file in order, with trailing
2260  values.  new-line characters. Alternatively, may be a string, in which case the string will be written without
2261    modification.
2262    
2263  =back  =back
2264    
2265  =cut  =cut
2266    
2267  sub UnEscape {  sub PutFile {
2268      # Get the parameter.      # Get the parameters.
2269      my ($codedString) = @_;      my ($fileName, $lines) = @_;
2270      # Initialize the return variable.      # Open the output file.
2271      my $retVal = "";      my $handle = Open(undef, ">$fileName");
2272      # Only proceed if the incoming string is nonempty.      # Count the lines written.
2273      if (defined $codedString) {      if (ref $lines ne 'ARRAY') {
2274          # Loop through the parameter string, looking for escape sequences. We can't do          # Here we have a scalar, so we write it raw.
2275          # translating because it causes problems with the escaped slash. ("\\t" becomes          print $handle $lines;
2276          # "\<tab>" no matter what we do.)          Trace("Scalar put to file $fileName.") if T(File => 3);
         while (length $codedString > 0) {  
             # Look for the first escape sequence.  
             if ($codedString =~ /^(.*?)\\(\\|n|t|r)/) {  
                 # Here we found it. The text preceding the sequence is in $1. The sequence  
                 # itself is in $2. First, move the clear text to the return variable.  
                 $retVal .= $1;  
                 $codedString = substr $codedString, (2 + length $1);  
                 # Get the escape value.  
                 my $char = $2;  
                 # If we have a "\r", we are done.  
                 if ($char ne 'r') {  
                     # Here it's not an 'r', so we convert it.  
                     $char =~ tr/\\tn/\\\t\n/;  
                     $retVal .= $char;  
                 }  
2277              } else {              } else {
2278                  # Here there are no more escape sequences. The rest of the string is          # Write the lines one at a time.
2279                  # transferred unmodified.          my $count = 0;
2280                  $retVal .= $codedString;          for my $line (@{$lines}) {
2281                  $codedString = "";              print $handle "$line\n";
2282              }              $count++;
2283          }          }
2284            Trace("$count lines put to file $fileName.") if T(File => 3);
2285      }      }
2286      # Return the result.      # Close the output file.
2287      return $retVal;      close $handle;
2288  }  }
2289    
2290  =head3 ParseRecord  =head3 ParseRecord
2291    
2292  C<< my @fields = Tracer::ParseRecord($line); >>      my @fields = Tracer::ParseRecord($line);
2293    
2294  Parse a tab-delimited data line. The data line is split into field values. Embedded tab  Parse a tab-delimited data line. The data line is split into field values. Embedded tab
2295  and new-line characters in the data line must be represented as C<\t> and C<\n>, respectively.  and new-line characters in the data line must be represented as C<\t> and C<\n>, respectively.
# Line 1521  Line 2334 
2334    
2335  =head3 Merge  =head3 Merge
2336    
2337  C<< my @mergedList = Tracer::Merge(@inputList); >>      my @mergedList = Tracer::Merge(@inputList);
2338    
2339  Sort a list of strings and remove duplicates.  Sort a list of strings and remove duplicates.
2340    
# Line 1567  Line 2380 
2380      return @inputList;      return @inputList;
2381  }  }
2382    
2383  =head3 Percent  =head3 Open
2384    
2385  C<< my $percent = Tracer::Percent($number, $base); >>      my $handle = Open($fileHandle, $fileSpec, $message);
2386    
2387  Returns the percent of the base represented by the given number. If the base  Open a file.
2388  is zero, returns zero.  
2389    The I<$fileSpec> is essentially the second argument of the PERL C<open>
2390    function. The mode is specified using Unix-like shell information. So, for
2391    example,
2392    
2393        Open(\*LOGFILE, '>>/usr/spool/news/twitlog', "Could not open twit log.");
2394    
2395    would open for output appended to the specified file, and
2396    
2397        Open(\*DATASTREAM, "| sort -u >$outputFile", "Could not open $outputFile.");
2398    
2399    would open a pipe that sorts the records written and removes duplicates. Note
2400    the use of file handle syntax in the Open call. To use anonymous file handles,
2401    code as follows.
2402    
2403        my $logFile = Open(undef, '>>/usr/spool/news/twitlog', "Could not open twit log.");
2404    
2405    The I<$message> parameter is used if the open fails. If it is set to C<0>, then
2406    the open returns TRUE if successful and FALSE if an error occurred. Otherwise, a
2407    failed open will throw an exception and the third parameter will be used to construct
2408    an error message. If the parameter is omitted, a standard message is constructed
2409    using the file spec.
2410    
2411        Could not open "/usr/spool/news/twitlog"
2412    
2413    Note that the mode characters are automatically cleaned from the file name.
2414    The actual error message from the file system will be captured and appended to the
2415    message in any case.
2416    
2417        Could not open "/usr/spool/news/twitlog": file not found.
2418    
2419    In some versions of PERL the only error message we get is a number, which
2420    corresponds to the C++ C<errno> value.
2421    
2422        Could not open "/usr/spool/news/twitlog": 6.
2423    
2424  =over 4  =over 4
2425    
2426  =item number  =item fileHandle
2427    
2428  Percent numerator.  File handle. If this parameter is C<undef>, a file handle will be generated
2429    and returned as the value of this method.
2430    
2431  =item base  =item fileSpec
2432    
2433  Percent base.  File name and mode, as per the PERL C<open> function.
2434    
2435    =item message (optional)
2436    
2437    Error message to use if the open fails. If omitted, a standard error message
2438    will be generated. In either case, the error information from the file system
2439    is appended to the message. To specify a conditional open that does not throw
2440    an error if it fails, use C<0>.
2441    
2442  =item RETURN  =item RETURN
2443    
2444  Returns the percentage of the base represented by the numerator.  Returns the name of the file handle assigned to the file, or C<undef> if the
2445    open failed.
2446    
2447  =back  =back
2448    
2449  =cut  =cut
2450    
2451  sub Percent {  sub Open {
2452      # Get the parameters.      # Get the parameters.
2453      my ($number, $base) = @_;      my ($fileHandle, $fileSpec, $message) = @_;
2454      # Declare the return variable.      # Attempt to open the file.
2455      my $retVal = 0;      my $rv = open $fileHandle, $fileSpec;
2456      # Compute the percent.      # If the open failed, generate an error message.
2457      if ($base != 0) {      if (! $rv) {
2458          $retVal = $number * 100 / $base;          # Save the system error message.
2459            my $sysMessage = $!;
2460            # See if we need a default message.
2461            if (!$message) {
2462                # Clean any obvious mode characters and leading spaces from the
2463                # filename.
2464                my ($fileName) = FindNamePart($fileSpec);
2465                $message = "Could not open \"$fileName\"";
2466            }
2467            # Terminate with an error using the supplied message and the
2468            # error message from the file system.
2469            Confess("$message: $!");
2470        }
2471        # Return the file handle.
2472        return $fileHandle;
2473    }
2474    
2475    =head3 FindNamePart
2476    
2477        my ($fileName, $start, $len) = Tracer::FindNamePart($fileSpec);
2478    
2479    Extract the portion of a file specification that contains the file name.
2480    
2481    A file specification is the string passed to an C<open> call. It specifies the file
2482    mode and name. In a truly complex situation, it can specify a pipe sequence. This
2483    method assumes that the file name is whatever follows the first angle bracket
2484    sequence.  So, for example, in the following strings the file name is
2485    C</usr/fig/myfile.txt>.
2486    
2487        >>/usr/fig/myfile.txt
2488        </usr/fig/myfile.txt
2489        | sort -u > /usr/fig/myfile.txt
2490    
2491    If the method cannot find a file name using its normal methods, it will return the
2492    whole incoming string.
2493    
2494    =over 4
2495    
2496    =item fileSpec
2497    
2498    File specification string from which the file name is to be extracted.
2499    
2500    =item RETURN
2501    
2502    Returns a three-element list. The first element contains the file name portion of
2503    the specified string, or the whole string if a file name cannot be found via normal
2504    methods. The second element contains the start position of the file name portion and
2505    the third element contains the length.
2506    
2507    =back
2508    
2509    =cut
2510    #: Return Type $;
2511    sub FindNamePart {
2512        # Get the parameters.
2513        my ($fileSpec) = @_;
2514        # Default to the whole input string.
2515        my ($retVal, $pos, $len) = ($fileSpec, 0, length $fileSpec);
2516        # Parse out the file name if we can.
2517        if ($fileSpec =~ m/(<|>>?)(.+?)(\s*)$/) {
2518            $retVal = $2;
2519            $len = length $retVal;
2520            $pos = (length $fileSpec) - (length $3) - $len;
2521      }      }
2522      # Return the result.      # Return the result.
2523      return $retVal;      return ($retVal, $pos, $len);
2524  }  }
2525    
2526  =head3 GetFile  =head3 OpenDir
2527    
2528  C<< my @fileContents = Tracer::GetFile($fileName); >>      my @files = OpenDir($dirName, $filtered, $flag);
2529    
2530      or  Open a directory and return all the file names. This function essentially performs
2531    the functions of an C<opendir> and C<readdir>. If the I<$filtered> parameter is
2532    set to TRUE, all filenames beginning with a period (C<.>), dollar sign (C<$>),
2533    or pound sign (C<#>) and all filenames ending with a tilde C<~>) will be
2534    filtered out of the return list. If the directory does not open and I<$flag> is not
2535    set, an exception is thrown. So, for example,
2536    
2537  C<< my $fileContents = Tracer::GetFile($fileName); >>      my @files = OpenDir("/Volumes/fig/contigs", 1);
2538    
2539  Return the entire contents of a file. In list context, line-ends are removed and  is effectively the same as
2540  each line is a list element. In scalar context, line-ends are replaced by C<\n>.  
2541        opendir(TMP, "/Volumes/fig/contigs") || Confess("Could not open /Volumes/fig/contigs.");
2542        my @files = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir(TMP);
2543    
2544    Similarly, the following code
2545    
2546        my @files = grep { $_ =~ /^\d/ } OpenDir("/Volumes/fig/orgs", 0, 1);
2547    
2548    Returns the names of all files in C</Volumes/fig/orgs> that begin with digits and
2549    automatically returns an empty list if the directory fails to open.
2550    
2551  =over 4  =over 4
2552    
2553  =item fileName  =item dirName
2554    
2555    Name of the directory to open.
2556    
2557    =item filtered
2558    
2559  Name of the file to read.  TRUE if files whose names begin with a period (C<.>) should be automatically removed
2560    from the list, else FALSE.
2561    
2562  =item RETURN  =item flag
2563    
2564  In a list context, returns the entire file as a list with the line terminators removed.  TRUE if a failure to open is okay, else FALSE
 In a scalar context, returns the entire file as a string. If an error occurs opening  
 the file, an empty list will be returned.  
2565    
2566  =back  =back
2567    
2568  =cut  =cut
2569    #: Return Type @;
2570  sub GetFile {  sub OpenDir {
2571      # Get the parameters.      # Get the parameters.
2572      my ($fileName) = @_;      my ($dirName, $filtered, $flag) = @_;
2573      # Declare the return variable.      # Declare the return variable.
2574      my @retVal = ();      my @retVal = ();
2575      # Open the file for input.      # Open the directory.
2576      my $handle = Open(undef, "<$fileName");      if (opendir(my $dirHandle, $dirName)) {
2577      # Read the whole file into the return variable, stripping off any terminator          # The directory opened successfully. Get the appropriate list according to the
2578      # characters.          # strictures of the filter parameter.
2579      my $lineCount = 0;          if ($filtered) {
2580      while (my $line = <$handle>) {              @retVal = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir $dirHandle;
         $lineCount++;  
         $line = Strip($line);  
         push @retVal, $line;  
     }  
     # Close it.  
     close $handle;  
     my $actualLines = @retVal;  
     Trace("$actualLines lines read from file $fileName.") if T(File => 2);  
     # Return the file's contents in the desired format.  
     if (wantarray) {  
         return @retVal;  
2581      } else {      } else {
2582          return join "\n", @retVal;              @retVal = readdir $dirHandle;
2583            }
2584            closedir $dirHandle;
2585        } elsif (! $flag) {
2586            # Here the directory would not open and it's considered an error.
2587            Confess("Could not open directory $dirName.");
2588      }      }
2589        # Return the result.
2590        return @retVal;
2591  }  }
2592    
 =head3 PutFile  
2593    
2594  C<< Tracer::PutFile($fileName, \@lines); >>  =head3 Insure
2595    
2596        Insure($dirName, $chmod);
2597    
2598  Write out a file from a list of lines of text.  Insure a directory is present.
2599    
2600  =over 4  =over 4
2601    
2602  =item fileName  =item dirName
2603    
2604  Name of the output file.  Name of the directory to check. If it does not exist, it will be created.
2605    
2606  =item lines  =item chmod (optional)
2607    
2608  Reference to a list of text lines. The lines will be written to the file in order, with trailing  Security privileges to be given to the directory if it is created.
 new-line characters. Alternatively, may be a string, in which case the string will be written without  
 modification.  
2609    
2610  =back  =back
2611    
2612  =cut  =cut
2613    
2614  sub PutFile {  sub Insure {
2615      # Get the parameters.      my ($dirName, $chmod) = @_;
2616      my ($fileName, $lines) = @_;      if (! -d $dirName) {
2617      # Open the output file.          Trace("Creating $dirName directory.") if T(2);
2618      my $handle = Open(undef, ">$fileName");          eval {
2619      # Count the lines written.              mkpath $dirName;
2620      if (ref $lines ne 'ARRAY') {              # If we have permissions specified, set them here.
2621          # Here we have a scalar, so we write it raw.              if (defined($chmod)) {
2622          print $handle $lines;                  chmod $chmod, $dirName;
2623          Trace("Scalar put to file $fileName.") if T(File => 3);              }
2624      } else {          };
2625          # Write the lines one at a time.          if ($@) {
2626          my $count = 0;              Confess("Error creating $dirName: $@");
         for my $line (@{$lines}) {  
             print $handle "$line\n";  
             $count++;  
2627          }          }
         Trace("$count lines put to file $fileName.") if T(File => 3);  
2628      }      }
     # Close the output file.  
     close $handle;  
2629  }  }
2630    
2631  =head3 QTrace  =head3 ChDir
2632    
2633  C<< my $data = QTrace($format); >>      ChDir($dirName);
2634    
2635  Return the queued trace data in the specified format.  Change to the specified directory.
2636    
2637  =over 4  =over 4
2638    
2639  =item format  =item dirName
2640    
2641  C<html> to format the data as an HTML list, C<text> to format it as straight text.  Name of the directory to which we want to change.
2642    
2643  =back  =back
2644    
2645  =cut  =cut
2646    
2647  sub QTrace {  sub ChDir {
2648      # Get the parameter.      my ($dirName) = @_;
2649      my ($format) = @_;      if (! -d $dirName) {
2650      # Create the return variable.          Confess("Cannot change to directory $dirName: no such directory.");
2651      my $retVal = "";      } else {
2652      # Only proceed if there is an actual queue.          Trace("Changing to directory $dirName.") if T(File => 4);
2653      if (@Queue) {          my $okFlag = chdir $dirName;
2654          # Process according to the format.          if (! $okFlag) {
2655          if ($format =~ m/^HTML$/i) {              Confess("Error switching to directory $dirName.");
             # Convert the queue into an HTML list.  
             $retVal = "<ul>\n";  
             for my $line (@Queue) {  
                 my $escapedLine = CGI::escapeHTML($line);  
                 $retVal .= "<li>$escapedLine</li>\n";  
             }  
             $retVal .= "</ul>\n";  
         } elsif ($format =~ m/^TEXT$/i) {  
             # Convert the queue into a list of text lines.  
             $retVal = join("\n", @Queue) . "\n";  
2656          }          }
         # Clear the queue.  
         @Queue = ();  
2657      }      }
     # Return the formatted list.  
     return $retVal;  
2658  }  }
2659    
2660  =head3 Confess  =head3 SetPermissions
   
 C<< Confess($message); >>  
2661    
2662  Trace the call stack and abort the program with the specified message. When used with      Tracer::SetPermissions($dirName, $group, $mask, %otherMasks);
 the OR operator and the L</Assert> method, B<Confess> can function as a debugging assert.  
 So, for example  
2663    
2664  C<< Assert($recNum >= 0) || Confess("Invalid record number $recNum."); >>  Set the permissions for a directory and all the files and folders inside it.
2665    In addition, the group ownership will be changed to the specified value.
2666    
2667  Will abort the program with a stack trace if the value of C<$recNum> is negative.  This method is more vulnerable than most to permission and compatability
2668    problems, so it does internal error recovery.
2669    
2670  =over 4  =over 4
2671    
2672  =item message  =item dirName
2673    
2674  Message to include in the trace.  Name of the directory to process.
2675    
2676  =back  =item group
2677    
2678  =cut  Name of the group to be assigned.
2679    
2680  sub Confess {  =item mask
     # Get the parameters.  
     my ($message) = @_;  
     # Trace the call stack.  
     Cluck($message);  
     # Abort the program.  
     croak(">>> $message");  
 }  
2681    
2682  =head3 Assert  Permission mask. Bits that are C<1> in this mask will be ORed into the
2683    permission bits of any file or directory that does not already have them
2684    set to 1.
2685    
2686  C<< Assert($condition1, $condition2, ... $conditionN); >>  =item otherMasks
2687    
2688  Return TRUE if all the conditions are true. This method can be used in conjunction with  Map of search patterns to permission masks. If a directory name matches
2689  the OR operator and the L</Confess> method as a debugging assert.  one of the patterns, that directory and all its members and subdirectories
2690  So, for example  will be assigned the new pattern. For example, the following would
2691    assign 0664 to most files, but would use 0777 for directories named C<tmp>.
2692    
2693        Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp$' => 01777);
2694    
2695  C<< Assert($recNum >= 0) || Confess("Invalid record number $recNum."); >>  The list is ordered, so the following would use 0777 for C<tmp1> and
2696    0666 for C<tmp>, C<tmp2>, or C<tmp3>.
2697    
2698  Will abort the program with a stack trace if the value of C<$recNum> is negative.      Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp1' => 0777,
2699                                                       '^tmp' => 0666);
2700    
2701    Note that the pattern matches are all case-insensitive, and only directory
2702    names are matched, not file names.
2703    
2704    =back
2705    
2706  =cut  =cut
2707  sub Assert {  
2708      my $retVal = 1;  sub SetPermissions {
2709      LOOP: for my $condition (@_) {      # Get the parameters.
2710          if (! $condition) {      my ($dirName, $group, $mask, @otherMasks) = @_;
2711              $retVal = 0;      # Set up for error recovery.
2712              last LOOP;      eval {
2713            # Switch to the specified directory.
2714            ChDir($dirName);
2715            # Get the group ID.
2716            my $gid = getgrnam($group);
2717            # Get the mask for tracing.
2718            my $traceMask = sprintf("%04o", $mask) . "($mask)";
2719            Trace("Fixing permissions for directory $dirName using group $group($gid) and mask $traceMask.") if T(File => 2);
2720            my $fixCount = 0;
2721            my $lookCount = 0;
2722            # @dirs will be a stack of directories to be processed.
2723            my @dirs = (getcwd());
2724            while (scalar(@dirs) > 0) {
2725                # Get the current directory.
2726                my $dir = pop @dirs;
2727                # Check for a match to one of the specified directory names. To do
2728                # that, we need to pull the individual part of the name off of the
2729                # whole path.
2730                my $simpleName = $dir;
2731                if ($dir =~ m!/([^/]+)$!) {
2732                    $simpleName = $1;
2733                }
2734                Trace("Simple directory name for $dir is $simpleName.") if T(File => 4);
2735                # Search for a match.
2736                my $match = 0;
2737                my $i;
2738                for ($i = 0; $i < $#otherMasks && ! $match; $i += 2) {
2739                    my $pattern = $otherMasks[$i];
2740                    if ($simpleName =~ /$pattern/i) {
2741                        $match = 1;
2742                    }
2743                }
2744                # Find out if we have a match. Note we use $i-1 because the loop added 2
2745                # before terminating due to the match.
2746                if ($match && $otherMasks[$i-1] != $mask) {
2747                    # This directory matches one of the incoming patterns, and it's
2748                    # a different mask, so we process it recursively with that mask.
2749                    SetPermissions($dir, $group, $otherMasks[$i-1], @otherMasks);
2750                } else {
2751                    # Here we can process normally. Get all of the non-hidden members.
2752                    my @submems = OpenDir($dir, 1);
2753                    for my $submem (@submems) {
2754                        # Get the full name.
2755                        my $thisMem = "$dir/$submem";
2756                        Trace("Checking member $thisMem.") if T(4);
2757                        $lookCount++;
2758                        if ($lookCount % 1000 == 0) {
2759                            Trace("$lookCount members examined. Current is $thisMem. Mask is $traceMask") if T(File => 3);
2760                        }
2761                        # Fix the group.
2762                        chown -1, $gid, $thisMem;
2763                        # Insure this member is not a symlink.
2764                        if (! -l $thisMem) {
2765                            # Get its info.
2766                            my $fileInfo = stat $thisMem;
2767                            # Only proceed if we got the info. Otherwise, it's a hard link
2768                            # and we want to skip it anyway.
2769                            if ($fileInfo) {
2770                                my $fileMode = $fileInfo->mode;
2771                                if (($fileMode & $mask) != $mask) {
2772                                    # Fix this member.
2773                                    $fileMode |= $mask;
2774                                    chmod $fileMode, $thisMem;
2775                                    $fixCount++;
2776                                }
2777                                # If it's a subdirectory, stack it.
2778                                if (-d $thisMem) {
2779                                    push @dirs, $thisMem;
2780          }          }
2781      }      }
     return $retVal;  
2782  }  }
2783                    }
2784  =head3 Cluck              }
2785            }
2786  C<< Cluck($message); >>          Trace("$lookCount files and directories processed, $fixCount fixed.") if T(File => 2);
2787        };
2788  Trace the call stack. Note that for best results, you should qualify the call with a      # Check for an error.
2789  trace condition. For example,      if ($@) {
2790            Confess("SetPermissions error: $@");
 C<< Cluck("Starting record parse.") if T(3); >>  
   
 will only trace the stack if the trace level for the package is 3 or more.  
   
 =over 4  
   
 =item message  
   
 Message to include in the trace.  
   
 =back  
   
 =cut  
   
 sub Cluck {  
     # Get the parameters.  
     my ($message) = @_;  
     # Trace what's happening.  
     Trace("Stack trace for event: $message");  
     my $confession = longmess($message);  
     # Convert the confession to a series of trace messages. Note we skip any  
     # messages relating to calls into Tracer.  
     for my $line (split /\s*\n/, $confession) {  
         Trace($line) if ($line !~ /Tracer\.pm/);  
2791      }      }
2792  }  }
2793    
2794  =head3 Min  =head3 GetLine
2795    
2796  C<< my $min = Min($value1, $value2, ... $valueN); >>      my @data = Tracer::GetLine($handle);
2797    
2798  Return the minimum argument. The arguments are treated as numbers.  Read a line of data from a tab-delimited file.
2799    
2800  =over 4  =over 4
2801    
2802  =item $value1, $value2, ... $valueN  =item handle
2803    
2804  List of numbers to compare.  Open file handle from which to read.
2805    
2806  =item RETURN  =item RETURN
2807    
2808  Returns the lowest number in the list.  Returns a list of the fields in the record read. The fields are presumed to be
2809    tab-delimited. If we are at the end of the file, then an empty list will be
2810    returned. If an empty line is read, a single list item consisting of a null
2811    string will be returned.
2812    
2813  =back  =back
2814    
2815  =cut  =cut
2816    
2817  sub Min {  sub GetLine {
2818      # Get the parameters. Note that we prime the return value with the first parameter.      # Get the parameters.
2819      my ($retVal, @values) = @_;      my ($handle) = @_;
2820      # Loop through the remaining parameters, looking for the lowest.      # Declare the return variable.
2821      for my $value (@values) {      my @retVal = ();
2822          if ($value < $retVal) {      Trace("File position is " . tell($handle) . ". EOF flag is " . eof($handle) . ".") if T(File => 4);
2823              $retVal = $value;      # Read from the file.
2824        my $line = <$handle>;
2825        # Only proceed if we found something.
2826        if (defined $line) {
2827            # Remove the new-line. We are a bit over-cautious here because the file may be coming in via an
2828            # upload control and have a nonstandard EOL combination.
2829            $line =~ s/(\r|\n)+$//;
2830            # Here we do some fancy tracing to help in debugging complicated EOL marks.
2831            if (T(File => 4)) {
2832                my $escapedLine = $line;
2833                $escapedLine =~ s/\n/\\n/g;
2834                $escapedLine =~ s/\r/\\r/g;
2835                $escapedLine =~ s/\t/\\t/g;
2836                Trace("Line read: -->$escapedLine<--");
2837            }
2838            # If the line is empty, return a single empty string; otherwise, parse
2839            # it into fields.
2840            if ($line eq "") {
2841                push @retVal, "";
2842            } else {
2843                push @retVal, split /\t/,$line;
2844          }          }
2845        } else {
2846            # Trace the reason the read failed.
2847            Trace("End of file: $!") if T(File => 3);
2848      }      }
2849      # Return the minimum found.      # Return the result.
2850      return $retVal;      return @retVal;
2851  }  }
2852    
2853  =head3 Max  =head3 PutLine
2854    
2855  C<< my $max = Max($value1, $value2, ... $valueN); >>      Tracer::PutLine($handle, \@fields, $eol);
2856    
2857  Return the maximum argument. The arguments are treated as numbers.  Write a line of data to a tab-delimited file. The specified field values will be
2858    output in tab-separated form, with a trailing new-line.
2859    
2860  =over 4  =over 4
2861    
2862  =item $value1, $value2, ... $valueN  =item handle
2863    
2864  List of numbers to compare.  Output file handle.
2865    
2866  =item RETURN  =item fields
2867    
2868  Returns the highest number in the list.  List of field values.
2869    
2870    =item eol (optional)
2871    
2872    End-of-line character (default is "\n").
2873    
2874  =back  =back
2875    
2876  =cut  =cut
2877    
2878  sub Max {  sub PutLine {
2879      # Get the parameters. Note that we prime the return value with the first parameter.      # Get the parameters.
2880      my ($retVal, @values) = @_;      my ($handle, $fields, $eol) = @_;
2881      # Loop through the remaining parameters, looking for the highest.      # Write the data.
2882      for my $value (@values) {      print $handle join("\t", @{$fields}) . ($eol || "\n");
         if ($value > $retVal) {  
             $retVal = $value;  
         }  
     }  
     # Return the maximum found.  
     return $retVal;  
2883  }  }
2884    
 =head3 AddToListMap  
   
 C<< Tracer::AddToListMap(\%hash, $key, $value1, $value2, ... valueN); >>  
2885    
2886  Add a key-value pair to a hash of lists. If no value exists for the key, a singleton list  =head3 PrintLine
 is created for the key. Otherwise, the new value is pushed onto the list.  
   
 =over 4  
   
 =item hash  
2887    
2888  Reference to the target hash.      Tracer::PrintLine($line);
2889    
2890  =item key  Print a line of text with a trailing new-line.
2891    
2892  Key for which the value is to be added.  =over 4
2893    
2894  =item value1, value2, ... valueN  =item line
2895    
2896  List of values to add to the key's value list.  Line of text to print.
2897    
2898  =back  =back
2899    
2900  =cut  =cut
2901    
2902  sub AddToListMap {  sub PrintLine {
2903      # Get the parameters.      # Get the parameters.
2904      my ($hash, $key, @values) = @_;      my ($line) = @_;
2905      # Process according to whether or not the key already has a value.      # Print the line.
2906      if (! exists $hash->{$key}) {      print "$line\n";
         $hash->{$key} = [@values];  
     } else {  
         push @{$hash->{$key}}, @values;  
     }  
2907  }  }
2908    
 =head3 DebugMode  
2909    
2910  C<< if (Tracer::DebugMode) { ...code... } >>  =head2 Other Useful Methods
2911    
2912    =head3 IDHASH
2913    
2914  Return TRUE if debug mode has been turned on, else abort.      my $hash = SHTargetSearch::IDHASH(@keys);
2915    
2916  Certain CGI scripts are too dangerous to exist in the production  This is a dinky little method that converts a list of values to a reference
2917  environment. This method provides a simple way to prevent them  to hash of values to labels. The values and labels are the same.
 from working unless they are explicitly turned on by creating a password  
 cookie via the B<SetPassword> script.  If debugging mode  
 is not turned on, an error will occur.  
2918    
2919  =cut  =cut
2920    
2921  sub DebugMode {  sub IDHASH {
2922      # Declare the return variable.      my %retVal = map { $_ => $_ } @_;
2923      my $retVal = 0;      return \%retVal;
     # Check the debug configuration.  
     my $password = CGI::cookie("DebugMode");  
     my $encrypted = Digest::MD5::md5_hex($password);  
     if ($encrypted eq "252dec43280e0c0d6a75ffcec486e61d") {  
         $retVal = 1;  
     } else {  
         # Here debug mode is off, so we generate an error.  
         Confess("Cannot use this facility without logging in.");  
     }  
     # Return the determination indicator.  
     return $retVal;  
2924  }  }
2925    
2926  =head3 Strip  =head3 Pluralize
2927    
2928  C<< my $string = Tracer::Strip($line); >>      my $plural = Tracer::Pluralize($word);
2929    
2930  Strip all line terminators off a string. This is necessary when dealing with files  This is a very simple pluralization utility. It adds an C<s> at the end
2931  that may have been transferred back and forth several times among different  of the input word unless it already ends in an C<s>, in which case it
2932  operating environments.  adds C<es>.
2933    
2934  =over 4  =over 4
2935    
2936  =item line  =item word
2937    
2938  Line of text to be stripped.  Singular word to pluralize.
2939    
2940  =item RETURN  =item RETURN
2941    
2942  The same line of text with all the line-ending characters chopped from the end.  Returns the probable plural form of the word.
2943    
2944  =back  =back
2945    
2946  =cut  =cut
2947    
2948  sub Strip {  sub Pluralize {
2949      # Get a copy of the parameter string.      # Get the parameters.
2950      my ($string) = @_;      my ($word) = @_;
2951      my $retVal = (defined $string ? $string : "");      # Declare the return variable.
2952      # Strip the line terminator characters.      my $retVal;
2953      $retVal =~ s/(\r|\n)+$//g;      if ($word =~ /s$/) {
2954            $retVal = $word . 'es';
2955        } else {
2956            $retVal = $word . 's';
2957        }
2958      # Return the result.      # Return the result.
2959      return $retVal;      return $retVal;
2960  }  }
2961    
2962  =head3 Pad  =head3 Numeric
2963    
2964  C<< my $paddedString = Tracer::Pad($string, $len, $left, $padChar); >>      my $okFlag = Tracer::Numeric($string);
2965    
2966  Pad a string to a specified length. The pad character will be a  Return the value of the specified string if it is numeric, or an undefined value
2967  space, and the padding will be on the right side unless specified  if it is not numeric.
 in the third parameter.  
2968    
2969  =over 4  =over 4
2970    
2971  =item string  =item string
2972    
2973  String to be padded.  String to check.
   
 =item len  
   
 Desired length of the padded string.  
   
 =item left (optional)  
   
 TRUE if the string is to be left-padded; otherwise it will be padded on the right.  
   
 =item padChar (optional)  
   
 Character to use for padding. The default is a space.  
2974    
2975  =item RETURN  =item RETURN
2976    
2977  Returns a copy of the original string with the pad character added to the  Returns the numeric value of the string if successful, or C<undef> if the string
2978  specified end so that it achieves the desired length.  is not numeric.
2979    
2980  =back  =back
2981    
2982  =cut  =cut
2983    
2984  sub Pad {  sub Numeric {
2985      # Get the parameters.      # Get the parameters.
2986      my ($string, $len, $left, $padChar) = @_;      my ($string) = @_;
2987      # Compute the padding character.      # We'll put the value in here if we succeed.
2988      if (! defined $padChar) {      my $retVal;
2989          $padChar = " ";      # Get a working copy of the string.
2990      }      my $copy = $string;
2991      # Compute the number of spaces needed.      # Trim leading and trailing spaces.
2992      my $needed = $len - length $string;      $copy =~ s/^\s+//;
2993      # Copy the string into the return variable.      $copy =~ s/\s+$//;
2994      my $retVal = $string;      # Check the result.
2995      # Only proceed if padding is needed.      if ($copy =~ /^[+-]?\d+$/) {
2996      if ($needed > 0) {          $retVal = $copy;
2997          # Create the pad string.      } elsif ($copy =~ /^([+-]\d+|\d*)[eE][+-]?\d+$/) {
2998          my $pad = $padChar x $needed;          $retVal = $copy;
2999          # Affix it to the return value.      } elsif ($copy =~ /^([+-]\d+|\d*)\.\d*([eE][+-]?\d+)?$/) {
3000          if ($left) {          $retVal = $copy;
             $retVal = $pad . $retVal;  
         } else {  
             $retVal .= $pad;  
         }  
3001      }      }
3002      # Return the result.      # Return the result.
3003      return $retVal;      return $retVal;
3004  }  }
3005    
 =head3 EOF  
   
 This is a constant that is lexically greater than any useful string.  
   
 =cut  
   
 sub EOF {  
     return "\xFF\xFF\xFF\xFF\xFF";  
 }  
   
 =head3 TICK  
   
 C<< my @results = TICK($commandString); >>  
   
 Perform a back-tick operation on a command. If this is a Windows environment, any leading  
 dot-slash (C<./> will be removed. So, for example, if you were doing  
   
     `./protein.cgi`  
3006    
3007  from inside a CGI script, it would work fine in Unix, but would issue an error message  =head3 ParseParm
 in Windows complaining that C<'.'> is not a valid command. If instead you code  
3008    
3009      TICK("./protein.cgi")      my $listValue = Tracer::ParseParm($string);
3010    
3011  it will work correctly in both environments.  Convert a parameter into a list reference. If the parameter is undefined,
3012    an undefined value will be returned. Otherwise, it will be parsed as a
3013    comma-separated list of values.
3014    
3015  =over 4  =over 4
3016    
3017  =item commandString  =item string
3018    
3019  The command string to pass to the system.  Incoming string.
3020    
3021  =item RETURN  =item RETURN
3022    
3023  Returns the standard output from the specified command, as a list.  Returns a reference to a list of values, or C<undef> if the incoming value
3024    was undefined.
3025    
3026  =back  =back
3027    
3028  =cut  =cut
 #: Return Type @;  
 sub TICK {  
     # Get the parameters.  
     my ($commandString) = @_;  
     # Chop off the dot-slash if this is Windows.  
     if ($FIG_Config::win_mode) {  
         $commandString =~ s!^\./!!;  
     }  
     # Activate the command and return the result.  
     return `$commandString`;  
 }  
   
 =head3 ScriptSetup  
   
 C<< my ($cgi, $varHash) = ScriptSetup($noTrace); >>  
   
 Perform standard tracing and debugging setup for scripts. The value returned is  
 the CGI object followed by a pre-built variable hash. At the end of the script,  
 the client should call L</ScriptFinish> to output the web page.  
   
 This method calls L</ETracing> to configure tracing, which allows the tracing  
 to be configured via the emergency tracing form on the debugging control panel.  
 Tracing will then be turned on automatically for all programs that use the L</ETracing>  
 method, which includes every program that uses this method or L</StandardSetup>.  
   
 =over 4  
3029    
3030  =item noTrace (optional)  sub ParseParm {
3031        # Get the parameters.
3032  If specified, tracing will be suppressed. This is useful if the script wants to set up      my ($string) = @_;
3033  tracing manually.      # Declare the return variable.
3034        my $retVal;
3035        # Check for data.
3036        if (defined $string) {
3037            # We have some, so split it into a list.
3038            $retVal = [ split /\s*,\s*/, $string];
3039        }
3040        # Return the result.
3041        return $retVal;
3042    }
3043    
3044  =item RETURN  =head3 Now
3045    
3046  Returns a two-element list consisting of a CGI query object and a variable hash for      my $string = Tracer::Now();
 the output page.  
3047    
3048  =back  Return a displayable time stamp containing the local time. Whatever format this
3049    method produces must be parseable by L</ParseDate>.
3050    
3051  =cut  =cut
3052    
3053  sub ScriptSetup {  sub Now {
3054      # Get the parameters.      return DisplayTime(time);
     my ($noTrace) = @_;  
     # Get the CGI query object.  
     my $cgi = CGI->new();  
     # Set up tracing if it's not suppressed.  
     ETracing($cgi) unless $noTrace;  
     # Create the variable hash.  
     my $varHash = { results => '' };  
     # Return the query object and variable hash.  
     return ($cgi, $varHash);  
3055  }  }
3056    
3057  =head3 ETracing  =head3 DisplayTime
3058    
3059  C<< ETracing($parameter); >>      my $string = Tracer::DisplayTime($time);
3060    
3061  Set up emergency tracing. Emergency tracing is tracing that is turned  Convert a time value to a displayable time stamp. Whatever format this
3062  on automatically for any program that calls this method. The emergency  method produces must be parseable by L</ParseDate>.
 tracing parameters are stored in a a file identified by a tracing key.  
 If this method is called with a CGI object, then the tracing key is  
 taken from a cookie. If it is called with no parameters, then the tracing  
 key is taken from an environment variable. If it is called with a string,  
 the tracing key is that string.  
3063    
3064  =over 4  =over 4
3065    
3066  =item parameter  =item time
3067    
3068  A parameter from which the tracing key is computed. If it is a scalar,  Time to display, in seconds since the epoch, or C<undef> if the time is unknown.
3069  that scalar is used as the tracing key. If it is a CGI object, the  
3070  tracing key is taken from the C<IP> cookie. If it is omitted, the  =item RETURN
3071  tracing key is taken from the C<TRACING> environment variable. If it  
3072  is a CGI object and emergency tracing is not on, the C<Trace> and  Returns a displayable time, or C<(n/a)> if the incoming time is undefined.
 C<TF> parameters will be used to determine the type of tracing.  
3073    
3074  =back  =back
3075    
3076  =cut  =cut
3077    
3078  sub ETracing {  sub DisplayTime {
3079      # Get the parameter.      my ($time) = @_;
3080      my ($parameter) = @_;      my $retVal = "(n/a)";
3081      # Check for CGI mode.      if (defined $time) {
3082      my $cgi = (ref $parameter eq 'CGI' ? $parameter : undef);          my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time);
3083      # Default to no tracing except errors.          $retVal = _p2($mon+1) . "/" . _p2($mday) . "/" . ($year + 1900) . " " .
3084      my ($tracing, $dest) = ("0", "WARN");                    _p2($hour) . ":" . _p2($min) . ":" . _p2($sec);
     # Check for emergency tracing.  
     my $tkey = EmergencyKey($parameter);  
     my $emergencyFile = EmergencyFileName($tkey);  
     if (-e $emergencyFile) {  
         # We have the file. Read in the data.  
         my @tracing = GetFile($emergencyFile);  
         # Pull off the time limit.  
         my $expire = shift @tracing;  
         # Convert it to seconds.  
         $expire *= 3600;  
         # Check the file data.  
         my $stat = stat($emergencyFile);  
         my ($now) = gettimeofday;  
         if ($now - $stat->mtime > $expire) {  
             # Delete the expired file.  
             unlink $emergencyFile;  
         } else {  
             # Emergency tracing is on. Pull off the destination and  
             # the trace level;  
             $dest = shift @tracing;  
             my $level = shift @tracing;  
             # Convert the destination to a real tracing destination.  
             # temp directory.  
             $dest = EmergencyTracingDest($tkey, $dest);  
             # Insure Tracer is specified.  
             my %moduleHash = map { $_ => 1 } @tracing;  
             $moduleHash{Tracer} = 1;  
             # Set the trace parameter.  
             $tracing = join(" ", $level, sort keys %moduleHash);  
         }  
     } elsif (defined $cgi) {  
         # There's no emergency tracing, but we have a CGI object, so check  
         # for tracing from the form parameters.  
         if ($cgi->param('Trace')) {  
             # Here the user has requested tracing via a form.  
             $dest = ($cgi->param('TF') ? ">$FIG_Config::temp/Trace$$.log" : "QUEUE");  
             $tracing = $cgi->param('Trace') . " Tracer";  
         }  
3085      }      }
3086      # Setup the tracing we've determined from all the stuff above.      return $retVal;
     TSetup($tracing, $dest);  
     # If we're a web script, trace the parameter and environment data.  
     if (defined $cgi) {  
         TraceParms($cgi);  
3087      }      }
3088    
3089    # Pad a number to 2 digits.
3090    sub _p2 {
3091        my ($value) = @_;
3092        $value = "0$value" if ($value < 10);
3093        return $value;
3094  }  }
3095    
3096  =head3 EmergencyFileName  =head3 Escape
3097    
3098  C<< my $fileName = Tracer::EmergencyFileName($tkey); >>      my $codedString = Tracer::Escape($realString);
3099    
3100  Return the emergency tracing file name. This is the file that specifies  Escape a string for use in a command. Tabs will be replaced by C<\t>, new-lines
3101  the tracing information.  replaced by C<\n>, carriage returns will be deleted, and backslashes will be doubled. The
3102    result is to reverse the effect of L</UnEscape>.
3103    
3104  =over 4  =over 4
3105    
3106  =item tkey  =item realString
3107    
3108  Tracing key for the current program.  String to escape.
3109    
3110  =item RETURN  =item RETURN
3111    
3112  Returns the name of the file to contain the emergency tracing information.  Escaped equivalent of the real string.
3113    
3114  =back  =back
3115    
3116  =cut  =cut
3117    
3118  sub EmergencyFileName {  sub Escape {
3119      # Get the parameters.      # Get the parameter.
3120      my ($tkey) = @_;      my ($realString) = @_;
3121      # Compute the emergency tracing file name.      # Initialize the return variable.
3122      return "$FIG_Config::temp/Emergency$tkey.txt";      my $retVal = "";
3123        # Loop through the parameter string, looking for sequences to escape.
3124        while (length $realString > 0) {
3125            # Look for the first sequence to escape.
3126            if ($realString =~ /^(.*?)([\n\t\r\\])/) {
3127                # Here we found it. The text preceding the sequence is in $1. The sequence
3128                # itself is in $2. First, move the clear text to the return variable.
3129                $retVal .= $1;
3130                # Strip the processed section off the real string.
3131                $realString = substr $realString, (length $2) + (length $1);
3132                # Get the matched character.
3133                my $char = $2;
3134                # If we have a CR, we are done.
3135                if ($char ne "\r") {
3136                    # It's not a CR, so encode the escape sequence.
3137                    $char =~ tr/\t\n/tn/;
3138                    $retVal .= "\\" . $char;
3139                }
3140            } else {
3141                # Here there are no more escape sequences. The rest of the string is
3142                # transferred unmodified.
3143                $retVal .= $realString;
3144                $realString = "";
3145            }
3146        }
3147        # Return the result.
3148        return $retVal;
3149  }  }
3150    
3151  =head3 EmergencyFileTarget  =head3 UnEscape
3152    
3153  C<< my $fileName = Tracer::EmergencyFileTarget($tkey); >>      my $realString = Tracer::UnEscape($codedString);
3154    
3155  Return the emergency tracing target file name. This is the file that receives  Replace escape sequences with their actual equivalents. C<\t> will be replaced by
3156  the tracing output for file-based tracing.  a tab, C<\n> by a new-line character, and C<\\> by a backslash. C<\r> codes will
3157    be deleted.
3158    
3159  =over 4  =over 4
3160    
3161  =item tkey  =item codedString
3162    
3163  Tracing key for the current program.  String to un-escape.
3164    
3165  =item RETURN  =item RETURN
3166    
3167  Returns the name of the file to contain the trace output.  Returns a copy of the original string with the escape sequences converted to their actual
3168    values.
3169    
3170  =back  =back
3171    
3172  =cut  =cut
3173    
3174  sub EmergencyFileTarget {  sub UnEscape {
3175      # Get the parameters.      # Get the parameter.
3176      my ($tkey) = @_;      my ($codedString) = @_;
3177      # Compute the emergency tracing file name.      # Initialize the return variable.
3178      return "$FIG_Config::temp/trace$tkey.log";      my $retVal = "";
3179        # Only proceed if the incoming string is nonempty.
3180        if (defined $codedString) {
3181            # Loop through the parameter string, looking for escape sequences. We can't do
3182            # translating because it causes problems with the escaped slash. ("\\t" becomes
3183            # "\<tab>" no matter what we do.)
3184            while (length $codedString > 0) {
3185                # Look for the first escape sequence.
3186                if ($codedString =~ /^(.*?)\\(\\|n|t|r)/) {
3187                    # Here we found it. The text preceding the sequence is in $1. The sequence
3188                    # itself is in $2. First, move the clear text to the return variable.
3189                    $retVal .= $1;
3190                    $codedString = substr $codedString, (2 + length $1);
3191                    # Get the escape value.
3192                    my $char = $2;
3193                    # If we have a "\r", we are done.
3194                    if ($char ne 'r') {
3195                        # Here it's not an 'r', so we convert it.
3196                        $char =~ tr/\\tn/\\\t\n/;
3197                        $retVal .= $char;
3198                    }
3199                } else {
3200                    # Here there are no more escape sequences. The rest of the string is
3201                    # transferred unmodified.
3202                    $retVal .= $codedString;
3203                    $codedString = "";
3204                }
3205            }
3206        }
3207        # Return the result.
3208        return $retVal;
3209  }  }
3210    
3211  =head3 EmergencyTracingDest  =head3 Percent
3212    
3213  C<< my $dest = Tracer::EmergencyTracingDest($tkey, $myDest); >>      my $percent = Tracer::Percent($number, $base);
3214    
3215  This method converts an emergency tracing destination to a real  Returns the percent of the base represented by the given number. If the base
3216  tracing destination. The main difference is that if the  is zero, returns zero.
 destination is C<FILE> or C<APPEND>, we convert it to file  
 output. If the destination is C<DUAL>, we convert it to file  
 and standard output.  
3217    
3218  =over 4  =over 4
3219    
3220  =item tkey  =item number
3221    
3222  Tracing key for this environment.  Percent numerator.
3223    
3224  =item myDest  =item base
3225    
3226  Destination from the emergency tracing file.  Percent base.
3227    
3228  =item RETURN  =item RETURN
3229    
3230  Returns a destination that can be passed into L</TSetup>.  Returns the percentage of the base represented by the numerator.
3231    
3232  =back  =back
3233    
3234  =cut  =cut
3235    
3236  sub EmergencyTracingDest {  sub Percent {
3237      # Get the parameters.      # Get the parameters.
3238      my ($tkey, $myDest) = @_;      my ($number, $base) = @_;
3239      # Declare the return variable.      # Declare the return variable.
3240      my $retVal;      my $retVal = 0;
3241      # Process according to the destination value.      # Compute the percent.
3242      if ($myDest eq 'FILE') {      if ($base != 0) {
3243          $retVal = ">" . EmergencyFileTarget($tkey);          $retVal = $number * 100 / $base;
     } elsif ($myDest eq 'APPEND') {  
         $retVal = ">>" . EmergencyFileTarget($tkey);  
     } elsif ($myDest eq 'DUAL') {  
         $retVal = "+>" . EmergencyFileTarget($tkey);  
3244      }      }
3245      # Return the result.      # Return the result.
3246      return $retVal;      return $retVal;
3247  }  }
3248    
3249  =head3 Emergency  =head3 In
3250    
3251  C<< Emergency($key, $hours, $dest, $level, @modules); >>      my $flag = Tracer::In($value, $min, $max);
3252    
3253  Turn on emergency tracing. This method is normally invoked over the web from  Return TRUE if the value is between the minimum and the maximum, else FALSE.
 a debugging console, but it can also be called by the C<trace.pl> script.  
 The caller specifies the duration of the emergency in hours, the desired tracing  
 destination, the trace level, and a list of the trace modules to activate.  
 For the length of the duration, when a program in an environment with the  
 specified tracing key active invokes a Sprout CGI script, tracing will be  
 turned on automatically. See L</TSetup> for more about tracing setup and  
 L</ETracing> for more about emergency tracing.  
3254    
3255  =over 4  =cut
3256    
3257  =item tkey  sub In {
3258        return ($_[0] <= $_[2] && $_[0] >= $_[1]);
3259    }
3260    
 The tracing key. This is used to identify the control file and the trace file.  
3261    
3262  =item hours  =head3 Constrain
3263    
3264  Number of hours to keep emergency tracing alive.      my $constrained = Constrain($value, $min, $max);
3265    
3266  =item dest  Modify a numeric value to bring it to a point in between a maximum and a minimum.
3267    
3268  Tracing destination. If no path information is specified for a file  =over 4
 destination, it is put in the FIG temporary directory.  
3269    
3270  =item level  =item value
3271    
3272  Tracing level. A higher level means more trace messages.  Value to constrain.
3273    
3274  =item modules  =item min (optional)
3275    
3276  A list of the tracing modules to activate.  Minimum permissible value. If this parameter is undefined, no minimum constraint will be applied.
3277    
3278    =item max (optional)
3279    
3280    Maximum permissible value. If this parameter is undefined, no maximum constraint will be applied.
3281    
3282    =item RETURN
3283    
3284    Returns the incoming value, constrained according to the other parameters.
3285    
3286  =back  =back
3287    
3288  =cut  =cut
3289    
3290  sub Emergency {  sub Constrain {
3291      # Get the parameters.      # Get the parameters.
3292      my ($tkey, $hours, $dest, $level, @modules) = @_;      my ($value, $min, $max) = @_;
3293      # Create the emergency file.      # Declare the return variable.
3294      my $specFile = EmergencyFileName($tkey);      my $retVal = $value;
3295      my $outHandle = Open(undef, ">$specFile");      # Apply the minimum constraint.
3296      print $outHandle join("\n", $hours, $dest, $level, @modules, "");      if (defined $min && $retVal < $min) {
3297            $retVal = $min;
3298        }
3299        # Apply the maximum constraint.
3300        if (defined $max && $retVal > $max) {
3301            $retVal = $max;
3302        }
3303        # Return the result.
3304        return $retVal;
3305  }  }
3306    
3307  =head3 EmergencyKey  =head3 Min
3308    
3309  C<< my $tkey = EmergencyKey($parameter); >>      my $min = Min($value1, $value2, ... $valueN);
3310    
3311  Return the Key to be used for emergency tracing. This could be an IP address,  Return the minimum argument. The arguments are treated as numbers.
  a session ID, or a user name, depending on the environment.  
3312    
3313  =over 4  =over 4
3314    
3315  =item parameter  =item $value1, $value2, ... $valueN
3316    
3317  Parameter defining the method for finding the tracing key. If it is a scalar,  List of numbers to compare.
 then it is presumed to be the tracing key itself. If it is a CGI object, then  
 the tracing key is taken from the C<IP> cookie. Otherwise, the tracing key is  
 taken from the C<TRACING> environment variable.  
3318    
3319  =item RETURN  =item RETURN
3320    
3321  Returns the key to be used for labels in emergency tracing.  Returns the lowest number in the list.
3322    
3323  =back  =back
3324    
3325  =cut  =cut
3326    
3327  sub EmergencyKey {  sub Min {
3328      # Get the parameters.      # Get the parameters. Note that we prime the return value with the first parameter.
3329      my ($parameter) = @_;      my ($retVal, @values) = @_;
3330      # Declare the return variable.      # Loop through the remaining parameters, looking for the lowest.
3331      my $retVal;      for my $value (@values) {
3332      # Determine the parameter type.          if ($value < $retVal) {
3333      if (! defined $parameter) {              $retVal = $value;
         # Here we're supposed to check the environment.  
         $retVal = $ENV{TRACING};  
     } else {  
         my $ptype = ref $parameter;  
         if ($ptype eq 'CGI') {  
             # Here we were invoked from a web page. Look for a cookie.  
             $retVal = $parameter->cookie('IP');  
         } elsif (! $ptype) {  
             # Here the key was passed in.  
             $retVal = $parameter;  
         }  
3334      }      }
     # If no luck finding a key, use the PID.  
     if (! defined $retVal) {  
         $retVal = $$;  
3335      }      }
3336      # Return the result.      # Return the minimum found.
3337      return $retVal;      return $retVal;
3338  }  }
3339    
3340    =head3 Max
3341    
3342  =head3 TraceParms      my $max = Max($value1, $value2, ... $valueN);
   
 C<< Tracer::TraceParms($cgi); >>  
3343    
3344  Trace the CGI parameters at trace level CGI => 3 and the environment variables  Return the maximum argument. The arguments are treated as numbers.
 at level CGI => 4.  
3345    
3346  =over 4  =over 4
3347    
3348  =item cgi  =item $value1, $value2, ... $valueN
3349    
3350  CGI query object containing the parameters to trace.  List of numbers to compare.
3351    
3352    =item RETURN
3353    
3354    Returns the highest number in the list.
3355    
3356  =back  =back
3357    
3358  =cut  =cut
3359    
3360  sub TraceParms {  sub Max {
3361      # Get the parameters.      # Get the parameters. Note that we prime the return value with the first parameter.
3362      my ($cgi) = @_;      my ($retVal, @values) = @_;
3363      if (T(CGI => 3)) {      # Loop through the remaining parameters, looking for the highest.
3364          # Here we want to trace the parameter data.      for my $value (@values) {
3365          my @names = $cgi->param;          if ($value > $retVal) {
3366          for my $parmName (sort @names) {              $retVal = $value;
             # Note we skip the Trace parameters, which are for our use only.  
             if ($parmName ne 'Trace' && $parmName ne 'TF') {  
                 my @values = $cgi->param($parmName);  
                 Trace("CGI: $parmName = " . join(", ", @values));  
             }  
         }  
         # Display the request method.  
         my $method = $cgi->request_method();  
         Trace("Method: $method");  
     }  
     if (T(CGI => 4)) {  
         # Here we want the environment data too.  
         for my $envName (sort keys %ENV) {  
             Trace("ENV: $envName = $ENV{$envName}");  
3367          }          }
3368      }      }
3369        # Return the maximum found.
3370        return $retVal;
3371  }  }
3372    
3373  =head3 ScriptFinish  =head3 Strip
3374    
3375  C<< ScriptFinish($webData, $varHash); >>      my $string = Tracer::Strip($line);
3376    
3377  Output a web page at the end of a script. Either the string to be output or the  Strip all line terminators off a string. This is necessary when dealing with files
3378  name of a template file can be specified. If the second parameter is omitted,  that may have been transferred back and forth several times among different
3379  it is assumed we have a string to be output; otherwise, it is assumed we have the  operating environments.
 name of a template file. The template should have the variable C<DebugData>  
 specified in any form that invokes a standard script. If debugging mode is turned  
 on, a form field will be put in that allows the user to enter tracing data.  
 Trace messages will be placed immediately before the terminal C<BODY> tag in  
 the output, formatted as a list.  
3380    
3381  A typical standard script would loook like the following.  =over 4
3382    
3383      BEGIN {  =item line
         # Print the HTML header.  
         print "CONTENT-TYPE: text/html\n\n";  
     }  
     use Tracer;  
     use CGI;  
     use FIG;  
     # ... more uses ...  
3384    
3385      my ($cgi, $varHash) = ScriptSetup();  Line of text to be stripped.
3386      eval {  
3387          # ... get data from $cgi, put it in $varHash ...  =item RETURN
3388      };  
3389      if ($@) {  The same line of text with all the line-ending characters chopped from the end.
3390          Trace("Script Error: $@") if T(0);  
3391    =back
3392    
3393    =cut
3394    
3395    sub Strip {
3396        # Get a copy of the parameter string.
3397        my ($string) = @_;
3398        my $retVal = (defined $string ? $string : "");
3399        # Strip the line terminator characters.
3400        $retVal =~ s/(\r|\n)+$//g;
3401        # Return the result.
3402        return $retVal;
3403      }      }
     ScriptFinish("Html/MyTemplate.html", $varHash);  
3404    
3405  The idea here is that even if the script fails, you'll see trace messages and  =head3 Trim
3406  useful output.  
3407        my $string = Tracer::Trim($line);
3408    
3409    Trim all spaces from the beginning and ending of a string.
3410    
3411  =over 4  =over 4
3412    
3413  =item webData  =item line
3414    
3415  A string containing either the full web page to be written to the output or the  Line of text to be trimmed.
 name of a template file from which the page is to be constructed. If the name  
 of a template file is specified, then the second parameter must be present;  
 otherwise, it must be absent.  
3416    
3417  =item varHash (optional)  =item RETURN
3418    
3419  If specified, then a reference to a hash mapping variable names for a template  The same line of text with all whitespace chopped off either end.
 to their values. The template file will be read into memory, and variable markers  
 will be replaced by data in this hash reference.  
3420    
3421  =back  =back
3422    
3423  =cut  =cut
3424    
3425  sub ScriptFinish {  sub Trim {
3426      # Get the parameters.      # Get a copy of the parameter string.
3427      my ($webData, $varHash) = @_;      my ($string) = @_;
3428      # Check for a template file situation.      my $retVal = (defined $string ? $string : "");
3429      my $outputString;      # Strip the front spaces.
3430      if (defined $varHash) {      $retVal =~ s/^\s+//;
3431          # Here we have a template file. We need to determine the template type.      # Strip the back spaces.
3432          my $template;      $retVal =~ s/\s+$//;
3433          if ($FIG_Config::template_url && $webData =~ /\.php$/) {      # Return the result.
3434              $template = "$FIG_Config::template_url/$webData";      return $retVal;
         } else {  
             $template = "<<$webData";  
         }  
         $outputString = PageBuilder::Build($template, $varHash, "Html");  
     } else {  
         # Here the user gave us a raw string.  
         $outputString = $webData;  
     }  
     # Check for trace messages.  
     if ($Destination ne "NONE" && $TraceLevel > 0) {  
         # We have trace messages, so we want to put them at the end of the body. This  
         # is either at the end of the whole string or at the beginning of the BODY  
         # end-tag.  
         my $pos = length $outputString;  
         if ($outputString =~ m#</body>#gi) {  
             $pos = (pos $outputString) - 7;  
         }  
         # If the trace messages were queued, we unroll them. Otherwise, we display the  
         # destination.  
         my $traceHtml;  
         if ($Destination eq "QUEUE") {  
             $traceHtml = QTrace('Html');  
         } elsif ($Destination =~ /^>>(.+)$/) {  
             # Here the tracing output it to a file. We code it as a hyperlink so the user  
             # can copy the file name into the clipboard easily.  
             my $actualDest = $1;  
             $traceHtml = "<p>Tracing output to $actualDest.</p>\n";  
         } else {  
             # Here we have one of the special destinations.  
             $traceHtml = "<P>Tracing output type is $Destination.</p>\n";  
         }  
         substr $outputString, $pos, 0, $traceHtml;  
     }  
     # Write the output string.  
     print $outputString;  
3435  }  }
3436    
3437  =head3 Insure  =head3 Pad
3438    
3439  C<< Insure($dirName); >>      my $paddedString = Tracer::Pad($string, $len, $left, $padChar);
3440    
3441  Insure a directory is present.  Pad a string to a specified length. The pad character will be a
3442    space, and the padding will be on the right side unless specified
3443    in the third parameter.
3444    
3445  =over 4  =over 4
3446    
3447  =item dirName  =item string
3448    
3449  Name of the directory to check. If it does not exist, it will be created.  String to be padded.
3450    
3451    =item len
3452    
3453    Desired length of the padded string.
3454    
3455    =item left (optional)
3456    
3457    TRUE if the string is to be left-padded; otherwise it will be padded on the right.
3458    
3459    =item padChar (optional)
3460    
3461    Character to use for padding. The default is a space.
3462    
3463    =item RETURN
3464    
3465    Returns a copy of the original string with the pad character added to the
3466    specified end so that it achieves the desired length.
3467    
3468  =back  =back
3469    
3470  =cut  =cut
3471    
3472  sub Insure {  sub Pad {
3473      my ($dirName) = @_;      # Get the parameters.
3474      if (! -d $dirName) {      my ($string, $len, $left, $padChar) = @_;
3475          Trace("Creating $dirName directory.") if T(File => 2);      # Compute the padding character.
3476          eval { mkpath $dirName; };      if (! defined $padChar) {
3477          if ($@) {          $padChar = " ";
3478              Confess("Error creating $dirName: $@");      }
3479        # Compute the number of spaces needed.
3480        my $needed = $len - length $string;
3481        # Copy the string into the return variable.
3482        my $retVal = $string;
3483        # Only proceed if padding is needed.
3484        if ($needed > 0) {
3485            # Create the pad string.
3486            my $pad = $padChar x $needed;
3487            # Affix it to the return value.
3488            if ($left) {
3489                $retVal = $pad . $retVal;
3490            } else {
3491                $retVal .= $pad;
3492          }          }
3493      }      }
3494        # Return the result.
3495        return $retVal;
3496  }  }
3497    
3498  =head3 ChDir  =head3 Quoted
3499    
3500  C<< ChDir($dirName); >>      my $string = Tracer::Quoted($var);
3501    
3502  Change to the specified directory.  Convert the specified value to a string and enclose it in single quotes.
3503    If it's undefined, the string C<undef> in angle brackets will be used
3504    instead.
3505    
3506  =over 4  =over 4
3507    
3508  =item dirName  =item var
3509    
3510    Value to quote.
3511    
3512    =item RETURN
3513    
3514  Name of the directory to which we want to change.  Returns a string enclosed in quotes, or an indication the value is undefined.
3515    
3516  =back  =back
3517    
3518  =cut  =cut
3519    
3520  sub ChDir {  sub Quoted {
3521      my ($dirName) = @_;      # Get the parameters.
3522      if (! -d $dirName) {      my ($var) = @_;
3523          Confess("Cannot change to directory $dirName: no such directory.");      # Declare the return variable.
3524        my $retVal;
3525        # Are we undefined?
3526        if (! defined $var) {
3527            $retVal = "<undef>";
3528      } else {      } else {
3529          Trace("Changing to directory $dirName.") if T(File => 4);          # No, so convert to a string and enclose in quotes.
3530          my $okFlag = chdir $dirName;          $retVal = $var;
3531          if (! $okFlag) {          $retVal =~ s/'/\\'/;
3532              Confess("Error switching to directory $dirName.");          $retVal = "'$retVal'";
         }  
3533      }      }
3534        # Return the result.
3535        return $retVal;
3536  }  }
3537    
3538  =head3 SendSMS  =head3 EOF
3539    
3540  C<< my $msgID = Tracer::SendSMS($phoneNumber, $msg); >>  This is a constant that is lexically greater than any useful string.
3541    
3542  Send a text message to a phone number using Clickatell. The FIG_Config file must contain the  =cut
 user name, password, and API ID for the relevant account in the hash reference variable  
 I<$FIG_Config::phone>, using the keys C<user>, C<password>, and C<api_id>. For  
 example, if the user name is C<BruceTheHumanPet>, the password is C<silly>, and the API ID  
 is C<2561022>, then the FIG_Config file must contain  
3543    
3544      $phone =  { user => 'BruceTheHumanPet',  sub EOF {
3545                  password => 'silly',      return "\xFF\xFF\xFF\xFF\xFF";
3546                  api_id => '2561022' };  }
3547    
3548  The original purpose of this method was to insure Bruce would be notified immediately when the  =head3 TICK
 Sprout Load terminates. Care should be taken if you do not wish Bruce to be notified immediately  
 when you call this method.  
3549    
3550  The message ID will be returned if successful, and C<undef> if an error occurs.      my @results = TICK($commandString);
3551    
3552  =over 4  Perform a back-tick operation on a command. If this is a Windows environment, any leading
3553    dot-slash (C<./> will be removed. So, for example, if you were doing
3554