[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.80, Fri Feb 9 22:53:22 2007 UTC revision 1.128, Wed Dec 16 20:57:35 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    
 =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 Public Methods  =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    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 347  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 369  Line 308 
308      $SetupCount++;      $SetupCount++;
309  }  }
310    
311  =head3 StandardSetup  =head3 SetLevel
   
 C<< my ($options, @parameters) = StandardSetup(\@categories, \%options, $parmHelp, @ARGV); >>  
   
 This method performs standard command-line parsing and tracing setup. The return  
 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.  
   
 This is a complex method that does a lot of grunt work. The parameters can  
 be more easily understood, however, once they are examined individually.  
   
 The I<categories> parameter is the most obtuse. It is a reference to a list of  
 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  
312    
313      ["Sprout", "SproutLoad", "ERDB"]      Tracer::SetLevel($newLevel);
314    
315  This would cause trace messages in the specified three packages to appear in  Modify the trace level. A higher trace level will cause more messages to appear.
 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.  
316    
317  =over 4  =over 4
318    
319  =item SQL  =item newLevel
   
 Traces SQL commands and activity.  
   
 =item Tracer  
320    
321  Traces error messages and call stacks.  Proposed new trace level.
322    
323  =back  =back
324    
325  C<SQL> is only turned on if the C<-sql> option is specified in the command line.  =cut
 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.  
326    
327      TransactFeatures -trace=3 -sql register ../xacts IDs.tbl  sub SetLevel {
328        $TraceLevel = $_[0];
329    }
330    
331  Standard tracing is output to the standard output and echoed to the file  =head3 ParseDate
 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  
332    
333  The default trace level is 2. To get all messages, specify a trace level of 4.      my $time = Tracer::ParseDate($dateString);
 For a genome-by-genome update, use 3.  
334    
335      TransactFeatures -trace=3 -sql -user=Bruce register ../xacts IDs.tbl  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  would send the trace output to C<traceBruce.log> in the temporary directory.  If a time of day is present, it must be in military time with two digits for
342    everything but the hour.
343    
344  The I<options> parameter is a reference to a hash containing the command-line  The year must be exactly four digits.
 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.  
345    
346  You can specify a different default trace level by setting C<$options->{trace}>  Additional stuff can be in the string. We presume it's time zones or weekdays or something
347  prior to calling this method.  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  An example at this point would help. Consider, for example, the command-line utility  It should be guaranteed that this method will parse the output of the L</Now> function.
 C<TransactFeatures>. It accepts a list of positional parameters plus the options  
 C<safe>, C<noAlias>, C<start>, and C<tblFiles>. To start up this command, we execute  
 the following code.  
351    
352      my ($options, @parameters) = Tracer::StandardSetup(["DocUtils"],  The parameters are as follows.
                         { 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);  
353    
354    =over 4
355    
356  The call to C<ParseCommand> specifies the default values for the options and  =item dateString
 stores the actual options in a hash that is returned as C<$options>. The  
 positional parameters are returned in C<@parameters>.  
357    
358  The following is a sample command line for C<TransactFeatures>.  The date string to convert.
359    
360      TransactFeatures -trace=2 -noAlias register ../xacts IDs.tbl  =item RETURN
361    
362  In this case, C<register>, C<../xacts>, and C<IDs.tbl> are the positional  Returns a PERL time, that is, a number of seconds since the epoch, or C<undef> if
363  parameters, and would find themselves in I<@parameters> after executing the  the date string is invalid. A valid date string must contain a month and day.
 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  
364    
365      { trace => 2, sql => 0, safe => 0,  =back
       noAlias => 1, start => ' ', tblFiles => 0 }  
366    
367  Use of C<StandardSetup> in this way provides a simple way of performing  =cut
 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.  
368    
369  If the C<background> option is specified on the command line, then the  # Universal month conversion table.
370  standard and error outputs will be directed to files in the temporary  use constant MONTHS => {    Jan =>  0, January   =>  0, '01' =>  0,  '1' =>  0,
371  directory, using the same suffix as the trace file. So, if the command                              Feb =>  1, February  =>  1, '02' =>  1,  '2' =>  1,
372  line specified                              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      -user=Bruce -background  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  then the trace output would go to C<traceBruce.log>, the standard output to  =head3 LogErrors
 C<outBruce.log>, and the error output to C<errBruce.log>. This is designed to  
 simplify starting a command in the background.  
419    
420  The user name is also used as the tracing key for L</Emergency Tracing>.      Tracer::LogErrors($fileName);
 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.  
421    
422  Finally, if the special option C<-h> is specified, the option names will  Route the standard error output to a log file.
 be traced at level 0 and the program will exit without processing.  
 This provides a limited help capability. For example, if the user enters  
423    
424      TransactFeatures -h  =over 4
425    
426  he would see the following output.  =item fileName
427    
428      TransactFeatures [options] command transactionDirectory IDfile  Name of the file to receive the error output.
         -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  
429    
430  The caller has the option of modifying the tracing scheme by placing a value  =back
 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,  
431    
432      { trace => [0, "tracing level (default 0)"],  =cut
        ...  
433    
434  would set the default trace level to 0 instead of E, while  sub LogErrors {
435        # Get the file name.
436        my ($fileName) = @_;
437        # Open the file as the standard error output.
438        open STDERR, '>', $fileName;
439    }
440    
441      { trace => ["2-", "tracing level (default 2)"],  =head3 Trace
        ...  
442    
443  would set the default to 2, but trace only to the log file, not to the      Trace($message);
 standard output.  
444    
445  The parameters to this method are as follows.  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  =over 4  =over 4
449    
450  =item categories  =item message
451    
452  Reference to a list of tracing category names. These should be names of  Message to write.
 packages whose internal workings will need to be debugged to get the  
 command working.  
453    
454  =item options  =back
455    
456  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).  
457    
458  =item parmHelp  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  A string that vaguely describes the positional parameters. This is used  =head3 MemTrace
 if the user specifies the C<-h> option.  
517    
518  =item argv      MemTrace($message);
519    
520  List of command line parameters, including the option switches, which must  Output a trace message that includes memory size information.
 precede the positional parameters and be prefixed by a hyphen.  
521    
522  =item RETURN  =over 4
523    
524  Returns a list. The first element of the list is the reference to a hash that  =item message
525  maps the command-line option switches to their values. These will either be the  
526  default values or overrides specified on the command line. The remaining  Message to display. The message will be followed by a sentence about the memory size.
 elements of the list are the position parameters, in order.  
527    
528  =back  =back
529    
530  =cut  =cut
531    
532  sub StandardSetup {  sub MemTrace {
533      # Get the parameters.      # Get the parameters.
534      my ($categories, $options, $parmHelp, @argv) = @_;      my ($message) = @_;
535      # Get the default tracing key.      my $memory = GetMemorySize();
536      my $tkey = EmergencyKey();      Trace("$message $memory in use.");
     # Add the tracing options.  
     if (! exists $options->{trace}) {  
         $options->{trace} = ['E', "tracing level (E for emergency tracing)"];  
537      }      }
538      $options->{sql} = [0, "turn on SQL tracing"];  
539      $options->{h} = [0, "display command-line options"];  
540      $options->{user} = [$tkey, "tracing key"];  =head3 TraceDump
541      $options->{background} = [0, "spool standard and error output"];  
542      # Create a parsing hash from the options hash. The parsing hash      TraceDump($title, $object);
543      # contains the default values rather than the default value  
544      # and the description. While we're at it, we'll memorize the  Dump an object to the trace log. This method simply calls the C<Dumper>
545      # length of the longest option name.  function, but routes the output to the trace log instead of returning it
546      my $longestName = 0;  as a string. The output is arranged so that it comes out monospaced when
547      my %parseOptions = ();  it appears in an HTML trace dump.
548      for my $key (keys %{$options}) {  
549          if (length $key > $longestName) {  =over 4
550              $longestName = length $key;  
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          $parseOptions{$key} = $options->{$key}->[0];  
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      }      }
     # 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";  
622      }      }
623      # Now we want to set up tracing. First, we need to know if the user          # Save the category name and level.
624      # wants emergency tracing.          $LastCategory = $category;
625      if ($retOptions->{trace} eq 'E') {          $LastLevel = $traceLevel;
626          ETracing($retOptions->{user});          # 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 {      } else {
858          # Here the tracing is controlled from the command line.                          $environment .= " referrer unknown.";
         my @cats = @{$categories};  
         if ($retOptions->{sql}) {  
             push @cats, "SQL";  
859          }          }
860          # Add the default categories.                      # Close off the sentence with the original link.
861          push @cats, "Tracer";                      $environment .= " URL of event is <a href=\"$url\">$url</a>.";
862          # Next, we create the category string by joining the categories.                  } else {
863          my $cats = join(" ", @cats);                      # No CGI object, so we're a command-line tool. Use the tracing
864          # Check to determine whether or not the caller wants to turn off tracing                      # key and the PID as the user identifier, and add the command.
865          # to the standard output.                      my $key = EmergencyKey();
866          my $traceLevel = $retOptions->{trace};                      $environment .= "Event Reported by $key process $$.";
867          my $textOKFlag = 1;                      if ($CommandLine) {
868          if ($traceLevel =~ /^(.)-/) {                          # We're in a StandardSetup script, so we have the real command line.
869              $traceLevel = $1;                          $environment .= "\n<pre>" . CGI::escapeHTML($CommandLine) . "</pre>\n";
870              $textOKFlag = 0;                      } 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          # Now we set up the trace mode.                  # Get the channel object.
934          my $traceMode;                  my $channel = $rss->{channel};
935          # Verify that we can open a file in the FIG temporary directory.                  # Update the last-build date.
936          my $traceFileName = "$FIG_Config::temp/trace$suffix.log";                  $channel->{lastBuildDate} = $date;
937          if (open TESTTRACE, ">$traceFileName") {                  # Get the item array.
938              # Here we can trace to a file.                  my $items = $channel->{item};
939              $traceMode = ">$traceFileName";                  # Insure it has only 100 entries.
940              if ($textOKFlag) {                  while (scalar @{$items} > 100) {
941                  # Echo to standard output if the text-OK flag is set.                      pop @{$items};
942                  $traceMode = "+$traceMode";                  }
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              # Close the test file.              }
957              close TESTTRACE;          }
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    =head3 ETracing
1064    
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 {          } else {
1116              # Here we can't trace to a file. We trace to the standard output if it's          $SavedCGI = undef;
1117              # okay, and the error log otherwise.      }
1118              if ($textOKFlag) {      # Check for the noParms option.
1119                  $traceMode = "TEXT";      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        my $emergencyFile = EmergencyFileName($tkey);
1126        if (-e $emergencyFile) {
1127            # We have the file. Read in the data.
1128            my @tracing = GetFile($emergencyFile);
1129            # Pull off the time limit.
1130            my $expire = shift @tracing;
1131            # Convert it to seconds.
1132            $expire *= 3600;
1133            # Check the file data.
1134            my $stat = stat($emergencyFile);
1135            my ($now) = gettimeofday;
1136            if ($now - $stat->mtime > $expire) {
1137                # Delete the expired file.
1138                unlink $emergencyFile;
1139              } else {              } else {
1140                  $traceMode = "WARN";              # Emergency tracing is on. Pull off the destination and
1141                # the trace level;
1142                $dest = shift @tracing;
1143                my $level = shift @tracing;
1144                # Insure Tracer is specified.
1145                my %moduleHash = map { $_ => 1 } @tracing;
1146                $moduleHash{Tracer} = 1;
1147                # Set the trace parameter.
1148                $tracing = join(" ", $level, sort keys %moduleHash);
1149            }
1150        }
1151        # Convert the destination to a real tracing destination.
1152        $dest = EmergencyTracingDest($tkey, $dest);
1153        # Setup the tracing we've determined from all the stuff above.
1154        TSetup($tracing, $dest);
1155        # Check to see if we're a web script.
1156        if (defined $SavedCGI) {
1157            # Yes we are. Trace the form and environment data if it's not suppressed.
1158            if (! $noParms) {
1159                TraceParms($SavedCGI);
1160            }
1161            # Check for RAW mode. In raw mode, we print a fake header so that we see everything
1162            # emitted by the script in its raw form.
1163            if (T(Raw => 3)) {
1164                print CGI::header(-type => 'text/plain', -tracing => 'Raw');
1165            }
1166        }
1167    }
1168    
1169    =head3 EmergencyFileName
1170    
1171        my $fileName = Tracer::EmergencyFileName($tkey);
1172    
1173    Return the emergency tracing file name. This is the file that specifies
1174    the tracing information.
1175    
1176    =over 4
1177    
1178    =item tkey
1179    
1180    Tracing key for the current program.
1181    
1182    =item RETURN
1183    
1184    Returns the name of the file to contain the emergency tracing information.
1185    
1186    =back
1187    
1188    =cut
1189    
1190    sub EmergencyFileName {
1191        # Get the parameters.
1192        my ($tkey) = @_;
1193        # Compute the emergency tracing file name.
1194        return "$FIG_Config::temp/Emergency$tkey.txt";
1195    }
1196    
1197    =head3 EmergencyFileTarget
1198    
1199        my $fileName = Tracer::EmergencyFileTarget($tkey);
1200    
1201    Return the emergency tracing target file name. This is the file that receives
1202    the tracing output for file-based tracing.
1203    
1204    =over 4
1205    
1206    =item tkey
1207    
1208    Tracing key for the current program.
1209    
1210    =item RETURN
1211    
1212    Returns the name of the file to contain the trace output.
1213    
1214    =back
1215    
1216    =cut
1217    
1218    sub EmergencyFileTarget {
1219        # Get the parameters.
1220        my ($tkey) = @_;
1221        # Compute the emergency tracing file name.
1222        return "$FIG_Config::temp/trace$tkey.log";
1223    }
1224    
1225    =head3 EmergencyTracingDest
1226    
1227        my $dest = Tracer::EmergencyTracingDest($tkey, $myDest);
1228    
1229    This method converts an emergency tracing destination to a real
1230    tracing destination. The main difference is that if the
1231    destination is C<FILE> or C<APPEND>, we convert it to file
1232    output. If the destination is C<DUAL>, we convert it to file
1233    and standard output.
1234    
1235    =over 4
1236    
1237    =item tkey
1238    
1239    Tracing key for this environment.
1240    
1241    =item myDest
1242    
1243    Destination from the emergency tracing file.
1244    
1245    =item RETURN
1246    
1247    Returns a destination that can be passed into L</TSetup>.
1248    
1249    =back
1250    
1251    =cut
1252    
1253    sub EmergencyTracingDest {
1254        # Get the parameters.
1255        my ($tkey, $myDest) = @_;
1256        # Declare the return variable.
1257        my $retVal = $myDest;
1258        # Process according to the destination value.
1259        if ($myDest eq 'FILE') {
1260            $retVal = ">" . EmergencyFileTarget($tkey);
1261        } elsif ($myDest eq 'APPEND') {
1262            $retVal = ">>" . EmergencyFileTarget($tkey);
1263        } elsif ($myDest eq 'DUAL') {
1264            $retVal = "+>" . EmergencyFileTarget($tkey);
1265        } elsif ($myDest eq 'WARN') {
1266            $retVal = "WARN";
1267              }              }
1268        # Return the result.
1269        return $retVal;
1270          }          }
1271          # Now set up the tracing.  
1272          TSetup("$traceLevel $cats", $traceMode);  =head3 Emergency
1273    
1274        Emergency($key, $hours, $dest, $level, @modules);
1275    
1276    Turn on emergency tracing. This method is normally invoked over the web from
1277    a debugging console, but it can also be called by the C<trace.pl> script.
1278    The caller specifies the duration of the emergency in hours, the desired tracing
1279    destination, the trace level, and a list of the trace modules to activate.
1280    For the length of the duration, when a program in an environment with the
1281    specified tracing key active invokes a Sprout CGI script, tracing will be
1282    turned on automatically. See L</TSetup> for more about tracing setup and
1283    L</ETracing> for more about emergency tracing.
1284    
1285    =over 4
1286    
1287    =item tkey
1288    
1289    The tracing key. This is used to identify the control file and the trace file.
1290    
1291    =item hours
1292    
1293    Number of hours to keep emergency tracing alive.
1294    
1295    =item dest
1296    
1297    Tracing destination. If no path information is specified for a file
1298    destination, it is put in the FIG temporary directory.
1299    
1300    =item level
1301    
1302    Tracing level. A higher level means more trace messages.
1303    
1304    =item modules
1305    
1306    A list of the tracing modules to activate.
1307    
1308    =back
1309    
1310    =cut
1311    
1312    sub Emergency {
1313        # Get the parameters.
1314        my ($tkey, $hours, $dest, $level, @modules) = @_;
1315        # Create the emergency file.
1316        my $specFile = EmergencyFileName($tkey);
1317        my $outHandle = Open(undef, ">$specFile");
1318        print $outHandle join("\n", $hours, $dest, $level, @modules, "");
1319      }      }
1320      # Check for the "h" option. If it is specified, dump the command-line  
1321      # options and exit the program.  =head3 EmergencyKey
1322      if ($retOptions->{h}) {  
1323          $0 =~ m#[/\\](\w+)(\.pl)?$#i;      my $tkey = EmergencyKey($parameter);
1324          print "$1 [options] $parmHelp\n";  
1325          for my $key (sort keys %{$options}) {  Return the Key to be used for emergency tracing. This could be an IP address,
1326              my $name = Pad($key, $longestName, 0, ' ');   a session ID, or a user name, depending on the environment.
1327              my $desc = $options->{$key}->[1];  
1328              if ($options->{$key}->[0]) {  =over 4
1329                  $desc .= " (default " . $options->{$key}->[0] . ")";  
1330    =item parameter
1331    
1332    Parameter defining the method for finding the tracing key. If it is a scalar,
1333    then it is presumed to be the tracing key itself. If it is a CGI object, then
1334    the tracing key is taken from the C<IP> cookie. Otherwise, the tracing key is
1335    taken from the C<TRACING> environment variable.
1336    
1337    =item RETURN
1338    
1339    Returns the key to be used for labels in emergency tracing.
1340    
1341    =back
1342    
1343    =cut
1344    
1345    sub EmergencyKey {
1346        # Get the parameters.
1347        my ($parameter) = @_;
1348        # Declare the return variable.
1349        my $retVal;
1350        # Determine the parameter type.
1351        if (! defined $parameter) {
1352            # Here we're supposed to check the environment. If that fails, we
1353            # get the effective login ID.
1354            $retVal = $ENV{TRACING} || scalar getpwuid($<);
1355        } else {
1356            my $ptype = ref $parameter;
1357            if ($ptype eq 'CGI') {
1358                # Here we were invoked from a web page. Look for a cookie.
1359                $retVal = $parameter->cookie('IP');
1360            } elsif (! $ptype) {
1361                # Here the key was passed in.
1362                $retVal = $parameter;
1363              }              }
             print "  $name $desc\n";  
1364          }          }
1365          exit(0);      # If no luck finding a key, use the PID.
1366        if (! defined $retVal) {
1367            $retVal = $$;
1368      }      }
1369      # Return the parsed parameters.      # Return the result.
1370      return ($retOptions, @retParameters);      return $retVal;
1371  }  }
1372    
 =head3 Setups  
1373    
1374  C<< my $count = Tracer::Setups(); >>  =head3 TraceParms
1375    
1376  Return the number of times L</TSetup> has been called.      Tracer::TraceParms($cgi);
1377    
1378  This method allows for the creation of conditional tracing setups where, for example, we  Trace the CGI parameters at trace level CGI => 3 and the environment variables
1379  may want to set up tracing if nobody else has done it before us.  at level CGI => 4. A self-referencing URL is traced at level CGI => 2.
1380    
1381    =over 4
1382    
1383    =item cgi
1384    
1385    CGI query object containing the parameters to trace.
1386    
1387    =back
1388    
1389  =cut  =cut
1390    
1391  sub Setups {  sub TraceParms {
1392      return $SetupCount;      # Get the parameters.
1393        my ($cgi) = @_;
1394        if (T(CGI => 2)) {
1395            # Here we trace the GET-style URL for the script, but only if it's
1396            # relatively small.
1397            my $url = $cgi->url(-relative => 1, -query => 1);
1398            my $len = length($url);
1399            if ($len < 500) {
1400                Trace("[URL] $url");
1401            } elsif ($len > 2048) {
1402                Trace("[URL] URL is too long to use with GET ($len characters).");
1403            } else {
1404                Trace("[URL] URL length is $len characters.");
1405            }
1406        }
1407        if (T(CGI => 3)) {
1408            # Here we want to trace the parameter data.
1409            my @names = $cgi->param;
1410            for my $parmName (sort @names) {
1411                # Note we skip the Trace parameters, which are for our use only.
1412                if ($parmName ne 'Trace' && $parmName ne 'TF') {
1413                    my @values = $cgi->param($parmName);
1414                    Trace("[CGI] $parmName = " . join(", ", @values));
1415                }
1416            }
1417            # Display the request method.
1418            my $method = $cgi->request_method();
1419            Trace("Method: $method");
1420        }
1421        if (T(CGI => 4)) {
1422            # Here we want the environment data too.
1423            for my $envName (sort keys %ENV) {
1424                Trace("[ENV] $envName = $ENV{$envName}");
1425            }
1426        }
1427  }  }
1428    
1429  =head3 Open  =head3 TraceImages
   
 C<< my $handle = Open($fileHandle, $fileSpec, $message); >>  
1430    
1431  Open a file.      Tracer::TraceImages($htmlString);
1432    
1433  The I<$fileSpec> is essentially the second argument of the PERL C<open>  Trace information about all of an html document's images. The tracing
1434  function. The mode is specified using Unix-like shell information. So, for  will be for type "IMG" at level 3. The image's source string
1435  example,  will be displayed. This is generally either the URL of the image or
1436    raw data for the image itself. If the source is too long, only the first 300
1437    characters will be shown at trace level 3. The entire source will be shown,
1438    however, at trace level 4. This method is not very smart, and might catch
1439    Javascript code, but it is still useful when debugging the arcane
1440    behavior of images in multiple browser environments.
1441    
1442      Open(\*LOGFILE, '>>/usr/spool/news/twitlog', "Could not open twit log.");  =over 4
1443    
1444  would open for output appended to the specified file, and  =item htmlString
1445    
1446      Open(\*DATASTREAM, "| sort -u >$outputFile", "Could not open $outputFile.");  HTML text for an outgoing web page.
1447    
1448  would open a pipe that sorts the records written and removes duplicates. Note  =back
 the use of file handle syntax in the Open call. To use anonymous file handles,  
 code as follows.  
1449    
1450      my $logFile = Open(undef, '>>/usr/spool/news/twitlog', "Could not open twit log.");  =cut
1451    
1452  The I<$message> parameter is used if the open fails. If it is set to C<0>, then  sub TraceImages {
1453  the open returns TRUE if successful and FALSE if an error occurred. Otherwise, a      # Only proceed if we're at the proper trace level.
1454  failed open will throw an exception and the third parameter will be used to construct      if (T(IMG => 3)) {
1455  an error message. If the parameter is omitted, a standard message is constructed          # For performance reasons we're manipulating $_[0] instead of retrieving the string
1456  using the file spec.          # into a variable called "$htmlString". This is because we expect html strings to be
1457            # long, and don't want to copy them any more than we have to.
1458            Trace(length($_[0]) . " characters in web page.");
1459            # Loop through the HTML, culling image tags.
1460            while ($_[0] =~ /<img\s+[^>]+?src="([^"]+)"/sgi) {
1461                # Extract the source string and determine whether or not it's too long.
1462                my $srcString = $1;
1463                my $pos = pos($_[0]) - length($srcString);
1464                my $excess = length($srcString) - 300;
1465                # We'll put the display string in here.
1466                my $srcDisplay = $srcString;
1467                # If it's a data string, split it at the comma.
1468                $srcDisplay =~ s/^(data[^,]+,)/$1\n/;
1469                # If there's no excess or we're at trace level 4, we're done. At level 3 with
1470                # a long string, however, we only show the first 300 characters.
1471                if ($excess > 0 && ! T(IMG => 4)) {
1472                    $srcDisplay = substr($srcDisplay,0,300) . "\nplus $excess characters.";
1473                }
1474                # Output the trace message.
1475                Trace("Image tag at position $pos:\n$srcDisplay");
1476            }
1477        }
1478    }
1479    
1480      Could not open "/usr/spool/news/twitlog"  =head2 Command-Line Utility Methods
1481    
1482  Note that the mode characters are automatically cleaned from the file name.  =head3 SendSMS
 The actual error message from the file system will be captured and appended to the  
 message in any case.  
1483    
1484      Could not open "/usr/spool/news/twitlog": file not found.      my $msgID = Tracer::SendSMS($phoneNumber, $msg);
1485    
1486  In some versions of PERL the only error message we get is a number, which  Send a text message to a phone number using Clickatell. The FIG_Config file must contain the
1487  corresponds to the C++ C<errno> value.  user name, password, and API ID for the relevant account in the hash reference variable
1488    I<$FIG_Config::phone>, using the keys C<user>, C<password>, and C<api_id>. For
1489    example, if the user name is C<BruceTheHumanPet>, the password is C<silly>, and the API ID
1490    is C<2561022>, then the FIG_Config file must contain
1491    
1492      Could not open "/usr/spool/news/twitlog": 6.      $phone =  { user => 'BruceTheHumanPet',
1493                    password => 'silly',
1494                    api_id => '2561022' };
1495    
1496  =over 4  The original purpose of this method was to insure Bruce would be notified immediately when the
1497    Sprout Load terminates. Care should be taken if you do not wish Bruce to be notified immediately
1498    when you call this method.
1499    
1500  =item fileHandle  The message ID will be returned if successful, and C<undef> if an error occurs.
1501    
1502  File handle. If this parameter is C<undef>, a file handle will be generated  =over 4
 and returned as the value of this method.  
1503    
1504  =item fileSpec  =item phoneNumber
1505    
1506  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
1507    would be prefixed by "1". A British phone number would be prefixed by "44".
1508    
1509  =item message (optional)  =item msg
1510    
1511  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>.  
1512    
1513  =item RETURN  =item RETURN
1514    
1515  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.  
1516    
1517  =back  =back
1518    
1519  =cut  =cut
1520    
1521  sub Open {  sub SendSMS {
1522      # Get the parameters.      # Get the parameters.
1523      my ($fileHandle, $fileSpec, $message) = @_;      my ($phoneNumber, $msg) = @_;
1524      # Attempt to open the file.      # Declare the return variable. If we do not change it, C<undef> will be returned.
1525      my $rv = open $fileHandle, $fileSpec;      my $retVal;
1526      # If the open failed, generate an error message.      # Only proceed if we have phone support.
1527      if (! $rv) {      if (! defined $FIG_Config::phone) {
1528          # Save the system error message.          Trace("Phone support not present in FIG_Config.") if T(1);
1529          my $sysMessage = $!;      } else {
1530          # See if we need a default message.          # Get the phone data.
1531          if (!$message) {          my $parms = $FIG_Config::phone;
1532              # Clean any obvious mode characters and leading spaces from the          # Get the Clickatell URL.
1533              # filename.          my $url = "http://api.clickatell.com/http/";
1534              my ($fileName) = FindNamePart($fileSpec);          # Create the user agent.
1535              $message = "Could not open \"$fileName\"";          my $ua = LWP::UserAgent->new;
1536            # Request a Clickatell session.
1537            my $resp = $ua->post("$url/sendmsg", { user => $parms->{user},
1538                                         password => $parms->{password},
1539                                         api_id => $parms->{api_id},
1540                                         to => $phoneNumber,
1541                                         text => $msg});
1542            # Check for an error.
1543            if (! $resp->is_success) {
1544                Trace("Alert failed.") if T(1);
1545            } else {
1546                # Get the message ID.
1547                my $rstring = $resp->content;
1548                if ($rstring =~ /^ID:\s+(.*)$/) {
1549                    $retVal = $1;
1550                } else {
1551                    Trace("Phone attempt failed with $rstring") if T(1);
1552          }          }
         # Terminate with an error using the supplied message and the  
         # error message from the file system.  
         Confess("$message: $!");  
1553      }      }
1554      # Return the file handle.      }
1555      return $fileHandle;      # Return the result.
1556        return $retVal;
1557  }  }
1558    
1559  =head3 FindNamePart  =head3 StandardSetup
1560    
1561  C<< my ($fileName, $start, $len) = Tracer::FindNamePart($fileSpec); >>      my ($options, @parameters) = StandardSetup(\@categories, \%options, $parmHelp, @ARGV);
1562    
1563  Extract the portion of a file specification that contains the file name.  This method performs standard command-line parsing and tracing setup. The return
1564    values are a hash of the command-line options and a list of the positional
1565    parameters. Tracing is automatically set up and the command-line options are
1566    validated.
1567    
1568  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
1569  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>.  
1570    
1571      >>/usr/fig/myfile.txt  The I<categories> parameter is the most obtuse. It is a reference to a list of
1572      </usr/fig/myfile.txt  special-purpose tracing categories. Most tracing categories are PERL package
1573      | sort -u > /usr/fig/myfile.txt  names. So, for example, if you wanted to turn on tracing inside the B<Sprout>,
1574    B<ERDB>, and B<SproutLoad> packages, you would specify the categories
1575    
1576  If the method cannot find a file name using its normal methods, it will return the      ["Sprout", "SproutLoad", "ERDB"]
1577  whole incoming string.  
1578    This would cause trace messages in the specified three packages to appear in
1579    the output. There are two special tracing categories that are automatically
1580    handled by this method. In other words, if you used L</TSetup> you would need
1581    to include these categories manually, but if you use this method they are turned
1582    on automatically.
1583    
1584  =over 4  =over 4
1585    
1586  =item fileSpec  =item SQL
1587    
1588  File specification string from which the file name is to be extracted.  Traces SQL commands and activity.
1589    
1590  =item RETURN  =item Tracer
1591    
1592  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.  
1593    
1594  =back  =back
1595    
1596  =cut  C<SQL> is only turned on if the C<-sql> option is specified in the command line.
1597  #: Return Type $;  The trace level is specified using the C<-trace> command-line option. For example,
1598  sub FindNamePart {  the following command line for C<TransactFeatures> turns on SQL tracing and runs
1599      # 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); >>  
1600    
1601  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,  
1602    
1603      my @files = OpenDir("/Volumes/fig/contigs", 1);  Standard tracing is output to the standard output and echoed to the file
1604    C<trace>I<$$>C<.log> in the FIG temporary directory, where I<$$> is the
1605    process ID. You can also specify the C<user> parameter to put a user ID
1606    instead of a process ID in the trace file name. So, for example
1607    
1608  is effectively the same as  The default trace level is 2. To get all messages, specify a trace level of 4.
1609    For a genome-by-genome update, use 3.
1610    
1611      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);  
1612    
1613  Similarly, the following code  would send the trace output to C<traceBruce.log> in the temporary directory.
1614    
1615      my @files = grep { $_ =~ /^\d/ } OpenDir("/Volumes/fig/orgs", 0, 1);  The I<options> parameter is a reference to a hash containing the command-line
1616    options, their default values, and an explanation of what they mean. Command-line
1617    options may be in the form of switches or keywords. In the case of a switch, the
1618    option value is 1 if it is specified and 0 if it is not specified. In the case
1619    of a keyword, the value is separated from the option name by an equal sign. You
1620    can see this last in the command-line example above.
1621    
1622  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}>
1623  automatically returns an empty list if the directory fails to open.  prior to calling this method.
1624    
1625  =over 4  An example at this point would help. Consider, for example, the command-line utility
1626    C<TransactFeatures>. It accepts a list of positional parameters plus the options
1627    C<safe>, C<noAlias>, C<start>, and C<tblFiles>. To start up this command, we execute
1628    the following code.
1629    
1630  =item dirName      my ($options, @parameters) = Tracer::StandardSetup(["DocUtils"],
1631                            { safe => [0, "use database transactions"],
1632                              noAlias => [0, "do not expect aliases in CHANGE transactions"],
1633                              start => [' ', "start with this genome"],
1634                              tblFiles => [0, "output TBL files containing the corrected IDs"] },
1635                            "<command> <transactionDirectory> <IDfile>",
1636                          @ARGV);
1637    
 Name of the directory to open.  
1638    
1639  =item filtered  The call to C<ParseCommand> specifies the default values for the options and
1640    stores the actual options in a hash that is returned as C<$options>. The
1641    positional parameters are returned in C<@parameters>.
1642    
1643  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.  
1644    
1645  =item flag      TransactFeatures -trace=2 -noAlias register ../xacts IDs.tbl
1646    
1647  TRUE if a failure to open is okay, else FALSE  Single and double hyphens are equivalent. So, you could also code the
1648    above command as
1649    
1650  =back      TransactFeatures --trace=2 --noAlias register ../xacts IDs.tbl
1651    
1652  =cut  In this case, C<register>, C<../xacts>, and C<IDs.tbl> are the positional
1653  #: Return Type @;  parameters, and would find themselves in I<@parameters> after executing the
1654  sub OpenDir {  above code fragment. The tracing would be set to level 2, and the categories
1655      # Get the parameters.  would be C<Tracer>, and <DocUtils>. C<Tracer> is standard,
1656      my ($dirName, $filtered, $flag) = @_;  and C<DocUtils> was included because it came in within the first parameter
1657      # 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;  
 }  
1658    
1659  =head3 SetLevel      { trace => 2, sql => 0, safe => 0,
1660          noAlias => 1, start => ' ', tblFiles => 0 }
1661    
1662  C<< Tracer::SetLevel($newLevel); >>  Use of C<StandardSetup> in this way provides a simple way of performing
1663    standard tracing setup and command-line parsing. Note that the caller is
1664    not even aware of the command-line switches C<-trace> and C<-sql>, which
1665    are used by this method to control the tracing. If additional tracing features
1666    need to be added in the future, they can be processed by this method without
1667    upsetting the command-line utilities.
1668    
1669  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
1670    standard and error outputs will be directed to files in the temporary
1671    directory, using the same suffix as the trace file. So, if the command
1672    line specified
1673    
1674  =over 4      -user=Bruce -background
1675    
1676  =item newLevel  then the trace output would go to C<traceBruce.log>, the standard output to
1677    C<outBruce.log>, and the error output to C<errBruce.log>. This is designed to
1678    simplify starting a command in the background.
1679    
1680  Proposed new trace level.  The user name is also used as the tracing key for L</Emergency Tracing>.
1681    Specifying a value of C<E> for the trace level causes emergency tracing to
1682    be used instead of custom tracing. If the user name is not specified,
1683    the tracing key is taken from the C<Tracing> environment variable. If there
1684    is no value for that variable, the tracing key will be computed from the active
1685    login ID.
1686    
1687  =back  Since the default situation in StandardSetup is to trace to the standard
1688    output, errors that occur in command-line scripts will not generate
1689    RSS events. To force the events, use the C<warn> option.
1690    
1691  =cut      TransactFeatures -background -warn register ../xacts IDs.tbl
1692    
1693  sub SetLevel {  Finally, if the special option C<-help> is specified, the option
1694      $TraceLevel = $_[0];  names will be traced at level 0 and the program will exit without processing.
1695  }  This provides a limited help capability. For example, if the user enters
1696    
1697  =head3 Now      TransactFeatures -help
1698    
1699  C<< my $string = Tracer::Now(); >>  he would see the following output.
1700    
1701  Return a displayable time stamp containing the local time.      TransactFeatures [options] <command> <transactionDirectory> <IDfile>
1702            -trace    tracing level (default E)
1703            -sql      trace SQL commands
1704            -safe     use database transactions
1705            -noAlias  do not expect aliases in CHANGE transactions
1706            -start    start with this genome
1707            -tblFiles output TBL files containing the corrected IDs
1708            -forked   do not erase the trace file before tracing
1709    
1710  =cut  The caller has the option of modifying the tracing scheme by placing a value
1711    for C<trace> in the incoming options hash. The default value can be overridden,
1712    or the tracing to the standard output can be turned off by suffixing a minus
1713    sign to the trace level. So, for example,
1714    
1715  sub Now {      { trace => [0, "tracing level (default 0)"],
1716      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;  
 }  
1717    
1718  # 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;  
 }  
1719    
1720  =head3 ParseTraceDate      { trace => ["2-", "tracing level (default 2)"],
1721           ...
1722    
1723  C<< my $time = Tracer::ParseTraceDate($dateString); >>  would set the default to 2, but trace only to the log file, not to the
1724    standard output.
1725    
1726  Convert a date from the trace file into a PERL timestamp.  The parameters to this method are as follows.
1727    
1728  =over 4  =over 4
1729    
1730  =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.  
1731    
1732  =back  Reference to a list of tracing category names. These should be names of
1733    packages whose internal workings will need to be debugged to get the
1734    command working.
1735    
1736  =cut  =item options
1737    
1738  sub ParseTraceDate {  Reference to a hash containing the legal options for the current command mapped
1739      # Get the parameters.  to their default values and descriptions. The user can override the defaults
1740      my ($dateString) = @_;  by specifying the options as command-line switches prefixed by a hyphen.
1741      # Declare the return variable.  Tracing-related options may be added to this hash. If the C<-h> option is
1742      my $retVal;  specified on the command line, the option descriptions will be used to
1743      # Parse the date.  explain the options. To turn off tracing to the standard output, add a
1744      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;  
 }  
1745    
1746  =head3 LogErrors  =item parmHelp
1747    
1748  C<< Tracer::LogErrors($fileName); >>  A string that vaguely describes the positional parameters. This is used
1749    if the user specifies the C<-h> option.
1750    
1751  Route the standard error output to a log file.  =item argv
1752    
1753  =over 4  List of command line parameters, including the option switches, which must
1754    precede the positional parameters and be prefixed by a hyphen.
1755    
1756  =item fileName  =item RETURN
1757    
1758  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
1759    maps the command-line option switches to their values. These will either be the
1760    default values or overrides specified on the command line. The remaining
1761    elements of the list are the position parameters, in order.
1762    
1763  =back  =back
1764    
1765  =cut  =cut
1766    
1767  sub LogErrors {  sub StandardSetup {
1768      # Get the file name.      # Get the parameters.
1769      my ($fileName) = @_;      my ($categories, $options, $parmHelp, @argv) = @_;
1770      # Open the file as the standard error output.      # Get the default tracing key.
1771      open STDERR, '>', $fileName;      my $tkey = EmergencyKey();
1772        # Save the command line.
1773        $CommandLine = join(" ", $0, map { $_ =~ /\s/ ? "\"$_\"" : $_ } @argv);
1774        # Add the tracing options.
1775        if (! exists $options->{trace}) {
1776            $options->{trace} = ['2', "tracing level (E for emergency tracing)"];
1777        }
1778        if (! exists $options->{forked}) {
1779            $options->{forked} = [0, "keep old trace file"];
1780        }
1781        $options->{sql} = [0, "turn on SQL tracing"];
1782        $options->{help} = [0, "display command-line options"];
1783        $options->{user} = [$tkey, "tracing key"];
1784        $options->{background} = [0, "spool standard and error output"];
1785        $options->{warn} = [0, "send errors to RSS feed"];
1786        $options->{moreTracing} = ["", "comma-delimited list of additional trace modules for debugging"];
1787        # Create a parsing hash from the options hash. The parsing hash
1788        # contains the default values rather than the default value
1789        # and the description. While we're at it, we'll memorize the
1790        # length of the longest option name.
1791        my $longestName = 0;
1792        my %parseOptions = ();
1793        for my $key (keys %{$options}) {
1794            if (length $key > $longestName) {
1795                $longestName = length $key;
1796            }
1797            $parseOptions{$key} = $options->{$key}->[0];
1798        }
1799        # Parse the command line.
1800        my ($retOptions, @retParameters) = ParseCommand(\%parseOptions, @argv);
1801        # Get the logfile suffix.
1802        my $suffix = $retOptions->{user};
1803        # We'll put the trace file name in here. We need it later if background
1804        # mode is on.
1805        my $traceFileName;
1806        # Now we want to set up tracing. First, we need to know if the user
1807        # wants emergency tracing.
1808        if ($retOptions->{trace} eq 'E') {
1809            ETracing($retOptions->{user});
1810        } else {
1811            # Here the tracing is controlled from the command line.
1812            my @cats = @{$categories};
1813            if ($retOptions->{sql}) {
1814                push @cats, "SQL";
1815            }
1816            if ($retOptions->{warn}) {
1817                push @cats, "Feed";
1818            }
1819            # Add the default categories.
1820            push @cats, "Tracer";
1821            # Check for more tracing groups.
1822            if ($retOptions->{moreTracing}) {
1823                push @cats, split /,/, $retOptions->{moreTracing};
1824            }
1825            # Next, we create the category string by joining the categories.
1826            my $cats = join(" ", @cats);
1827            # Check to determine whether or not the caller wants to turn off tracing
1828            # to the standard output.
1829            my $traceLevel = $retOptions->{trace};
1830            my $textOKFlag = 1;
1831            if ($traceLevel =~ /^(.)-/) {
1832                $traceLevel = $1;
1833                $textOKFlag = 0;
1834            }
1835            # Now we set up the trace mode.
1836            my $traceMode;
1837            # Verify that we can open a file in the FIG temporary directory.
1838            my $traceFileName = "$FIG_Config::temp/trace$suffix.log";
1839            my $traceFileSpec = ($retOptions->{forked} ? ">>$traceFileName" : ">$traceFileName");
1840            if (open TESTTRACE, "$traceFileSpec") {
1841                # Here we can trace to a file.
1842                $traceMode = ">>$traceFileName";
1843                if ($textOKFlag) {
1844                    # Echo to standard output if the text-OK flag is set.
1845                    $traceMode = "+$traceMode";
1846                }
1847                # Close the test file.
1848                close TESTTRACE;
1849            } else {
1850                # Here we can't trace to a file. Complain about this.
1851                warn "Could not open trace file $traceFileName: $!\n";
1852                # We trace to the standard output if it's
1853                # okay, and the error log otherwise.
1854                if ($textOKFlag) {
1855                    $traceMode = "TEXT";
1856                } else {
1857                    $traceMode = "WARN";
1858                }
1859            }
1860            # Now set up the tracing.
1861            TSetup("$traceLevel $cats", $traceMode);
1862        }
1863        # Check for background mode.
1864        if ($retOptions->{background}) {
1865            my $outFileName = "$FIG_Config::temp/out$suffix$$.log";
1866            my $errFileName = "$FIG_Config::temp/err$suffix$$.log";
1867            # Spool the output.
1868            open STDOUT, ">$outFileName";
1869            # If we have a trace file, trace the errors to the log. Otherwise,
1870            # spool the errors.
1871            if (defined $traceFileName) {
1872                open STDERR, "| Tracer $traceFileName";
1873            } else {
1874                open STDERR, ">$errFileName";
1875            }
1876            # Check for phone support. If we have phone support and a phone number,
1877            # we want to turn it on.
1878            if ($ENV{PHONE} && defined($FIG_Config::phone)) {
1879                $retOptions->{phone} = $ENV{PHONE};
1880            }
1881        }
1882        # Check for the "help" option. If it is specified, dump the command-line
1883        # options and exit the program.
1884        if ($retOptions->{help}) {
1885            $0 =~ m#[/\\](\w+)(\.pl)?$#i;
1886            print "$1 [options] $parmHelp\n";
1887            for my $key (sort keys %{$options}) {
1888                my $name = Pad($key, $longestName, 0, ' ');
1889                my $desc = $options->{$key}->[1];
1890                if ($options->{$key}->[0]) {
1891                    $desc .= " (default " . $options->{$key}->[0] . ")";
1892                }
1893                print "  $name $desc\n";
1894            }
1895            exit(0);
1896        }
1897        # Trace the options, if applicable.
1898        if (T(3)) {
1899            my @parms = grep { $retOptions->{$_} } keys %{$retOptions};
1900            Trace("Selected options: " . join(", ", sort @parms) . ".");
1901        }
1902        # Return the parsed parameters.
1903        return ($retOptions, @retParameters);
1904  }  }
1905    
1906  =head3 ReadOptions  =head3 ReadOptions
1907    
1908  C<< my %options = Tracer::ReadOptions($fileName); >>      my %options = Tracer::ReadOptions($fileName);
1909    
1910  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
1911  format  format
# Line 1056  Line 1966 
1966    
1967  =head3 GetOptions  =head3 GetOptions
1968    
1969  C<< Tracer::GetOptions(\%defaults, \%options); >>      Tracer::GetOptions(\%defaults, \%options);
1970    
1971  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
1972  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 1065  Line 1975 
1975    
1976  Consider the following example.  Consider the following example.
1977    
1978  C<< my $optionTable = GetOptions({ dbType => 'mySQL', trace => 0 }, $options); >>      my $optionTable = GetOptions({ dbType => 'mySQL', trace => 0 }, $options);
1979    
1980  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
1981  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 1073  Line 1983 
1983  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
1984  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
1985    
1986  C<< {databaseType => 'Oracle'} >>      {databaseType => 'Oracle'}
1987    
1988  an error will occur because the B<databaseType> option does not exist.  an error will occur because the B<databaseType> option does not exist.
1989    
# Line 1117  Line 2027 
2027    
2028  =head3 MergeOptions  =head3 MergeOptions
2029    
2030  C<< Tracer::MergeOptions(\%table, \%defaults); >>      Tracer::MergeOptions(\%table, \%defaults);
2031    
2032  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
2033  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 1149  Line 2059 
2059      }      }
2060  }  }
2061    
2062  =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  
2063    
2064  C<< my $switch = T($traceLevel); >>      my $optionString = Tracer::UnparseOptions(\%options);
2065    
2066  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
2067  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
2068    produce the same ultimate result when parsed by L</StandardSetup>.
2069    
2070  =over 4  =over 4
2071    
2072  =item category  =item options
   
 Category to which the message belongs. If not specified, the caller's package name is  
 used.  
   
 =item traceLevel  
2073    
2074  Relevant tracing level.  Reference to a hash of options to convert into an option string.
2075    
2076  =item RETURN  =item RETURN
2077    
2078  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
2079    parsed by L</StandardSetup>.
2080    
2081  =back  =back
2082    
2083  =cut  =cut
2084    
2085  sub T {  sub UnparseOptions {
     # Declare the return variable.  
     my $retVal = 0;  
     # Only proceed if tracing is turned on.  
     if ($Destination ne "NONE") {  
2086          # Get the parameters.          # Get the parameters.
2087          my ($category, $traceLevel) = @_;      my ($options) = @_;
2088          if (!defined $traceLevel) {      # The option segments will be put in here.
2089              # Here we have no category, so we need to get the calling package.      my @retVal = ();
2090              # The calling package is normally the first parameter. If it is      # Loop through the options.
2091              # omitted, the first parameter will be the tracelevel. So, the      for my $key (keys %$options) {
2092              # first thing we do is shift the so-called category into the          # Get the option value.
2093              # $traceLevel variable where it belongs.          my $value = $options->{$key};
2094              $traceLevel = $category;          # Only use it if it's nonempty.
2095              my ($package, $fileName, $line) = caller;          if (defined $value && $value ne "") {
2096              # If there is no calling package, we default to "main".              my $segment = "--$key=$value";
2097              if (!$package) {              # Quote it if necessary.
2098                  $category = "main";              if ($segment =~ /[ |<>*]/) {
2099              } else {                  $segment = '"' . $segment . '"';
                 $category = $package;  
             }  
2100          }          }
2101          # Save the category name.              # Add it to the return list.
2102          $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.");  
2103          }          }
         $retVal = ($traceLevel <= $TraceLevel && ($AllTrace || exists $Categories{$category}));  
2104      }      }
2105      # Return the computed result.      # Return the result.
2106      return $retVal;      return join(" ", @retVal);
2107  }  }
2108    
2109  =head3 ParseCommand  =head3 ParseCommand
2110    
2111  C<< my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList); >>      my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList);
2112    
2113  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
2114  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
2115  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
2116  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.
2117    
2118  C<< my ($options, @arguments) = ParseCommand({ errors => 0, logFile => 'trace.log'}, @words); >>      my ($options, @arguments) = ParseCommand({ errors => 0, logFile => 'trace.log'}, @words);
2119    
2120  In this case, the list @words will be treated as a command line. There are two options available,  In this case, the list @words will be treated as a command line and there are two options available,
2121  B<errors> and B<logFile>. If @words has the following format  B<errors> and B<logFile>. If @words has the following format
2122    
2123  C<< -logFile=error.log apple orange rutabaga >>      -logFile=error.log apple orange rutabaga
2124    
2125  then at the end of the invocation, C<$options> will be  then at the end of the invocation, C<$options> will be
2126    
2127  C<< { errors => 0, logFile => 'error.log' } >>      { errors => 0, logFile => 'error.log' }
2128    
2129  and C<@arguments> will contain  and C<@arguments> will contain
2130    
2131  C<< apple orange rutabaga >>      apple orange rutabaga
2132    
2133  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
2134  support for quote characters.  support for quote characters. Options can be specified with single or double hyphens.
2135    
2136  =over 4  =over 4
2137    
# Line 1320  Line 2156 
2156      my ($optionTable, @inputList) = @_;      my ($optionTable, @inputList) = @_;
2157      # Process any options in the input list.      # Process any options in the input list.
2158      my %overrides = ();      my %overrides = ();
2159      while ((@inputList > 0) && ($inputList[0] =~ /^-/)) {      while ((@inputList > 0) && ($inputList[0] =~ /^--?/)) {
2160          # Get the current option.          # Get the current option.
2161          my $arg = shift @inputList;          my $arg = shift @inputList;
2162          # Pull out the option name.          # Pull out the option name.
2163          $arg =~ /^-([^=]*)/g;          $arg =~ /^--?([^=]*)/g;
2164          my $name = $1;          my $name = $1;
2165          # Check for an option value.          # Check for an option value.
2166          if ($arg =~ /\G=(.*)$/g) {          if ($arg =~ /\G=(.*)$/g) {
# Line 1346  Line 2182 
2182      return ($optionTable, @retVal);      return ($optionTable, @retVal);
2183  }  }
2184    
 =head3 Escape  
2185    
2186  C<< my $codedString = Tracer::Escape($realString); >>  =head2 File Utility Methods
2187    
2188  Escape a string for use in a command length. Tabs will be replaced by C<\t>, new-lines  =head3 GetFile
2189  replaced by C<\n>, carriage returns will be deleted, and backslashes will be doubled. The  
2190  result is to reverse the effect of L</UnEscape>.      my @fileContents = Tracer::GetFile($fileName);
2191    
2192        or
2193    
2194        my $fileContents = Tracer::GetFile($fileName);
2195    
2196    Return the entire contents of a file. In list context, line-ends are removed and
2197    each line is a list element. In scalar context, line-ends are replaced by C<\n>.
2198    
2199  =over 4  =over 4
2200    
2201  =item realString  =item fileName
2202    
2203  String to escape.  Name of the file to read.
2204    
2205  =item RETURN  =item RETURN
2206    
2207  Escaped equivalent of the real string.  In a list context, returns the entire file as a list with the line terminators removed.
2208    In a scalar context, returns the entire file as a string. If an error occurs opening
2209    the file, an empty list will be returned.
2210    
2211  =back  =back
2212    
2213  =cut  =cut
2214    
2215  sub Escape {  sub GetFile {
2216      # Get the parameter.      # Get the parameters.
2217      my ($realString) = @_;      my ($fileName) = @_;
2218      # Initialize the return variable.      # Declare the return variable.
2219      my $retVal = "";      my @retVal = ();
2220      # Loop through the parameter string, looking for sequences to escape.      # Open the file for input.
2221      while (length $realString > 0) {      my $handle = Open(undef, "<$fileName");
2222          # Look for the first sequence to escape.      # Read the whole file into the return variable, stripping off any terminator
2223          if ($realString =~ /^(.*?)([\n\t\r\\])/) {      # characters.
2224              # Here we found it. The text preceding the sequence is in $1. The sequence      my $lineCount = 0;
2225              # itself is in $2. First, move the clear text to the return variable.      while (my $line = <$handle>) {
2226              $retVal .= $1;          $lineCount++;
2227              # Strip the processed section off the real string.          $line = Strip($line);
2228              $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;  
2229              }              }
2230        # Close it.
2231        close $handle;
2232        my $actualLines = @retVal;
2233        Trace("$actualLines lines read from file $fileName.") if T(File => 2);
2234        # Return the file's contents in the desired format.
2235        if (wantarray) {
2236            return @retVal;
2237          } else {          } else {
2238              # Here there are no more escape sequences. The rest of the string is          return join "\n", @retVal;
             # transferred unmodified.  
             $retVal .= $realString;  
             $realString = "";  
         }  
2239      }      }
     # Return the result.  
     return $retVal;  
2240  }  }
2241    
2242  =head3 UnEscape  =head3 PutFile
2243    
2244  C<< my $realString = Tracer::UnEscape($codedString); >>      Tracer::PutFile($fileName, \@lines);
2245    
2246  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.  
2247    
2248  =over 4  =over 4
2249    
2250  =item codedString  =item fileName
2251    
2252  String to un-escape.  Name of the output file.
2253    
2254  =item RETURN  =item lines
2255    
2256  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
2257  values.  new-line characters. Alternatively, may be a string, in which case the string will be written without
2258    modification.
2259    
2260  =back  =back
2261    
2262  =cut  =cut
2263    
2264  sub UnEscape {  sub PutFile {
2265      # Get the parameter.      # Get the parameters.
2266      my ($codedString) = @_;      my ($fileName, $lines) = @_;
2267      # Initialize the return variable.      # Open the output file.
2268      my $retVal = "";      my $handle = Open(undef, ">$fileName");
2269      # Only proceed if the incoming string is nonempty.      # Count the lines written.
2270      if (defined $codedString) {      if (ref $lines ne 'ARRAY') {
2271          # Loop through the parameter string, looking for escape sequences. We can't do          # Here we have a scalar, so we write it raw.
2272          # translating because it causes problems with the escaped slash. ("\\t" becomes          print $handle $lines;
2273          # "\<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;  
                 }  
2274              } else {              } else {
2275                  # Here there are no more escape sequences. The rest of the string is          # Write the lines one at a time.
2276                  # transferred unmodified.          my $count = 0;
2277                  $retVal .= $codedString;          for my $line (@{$lines}) {
2278                  $codedString = "";              print $handle "$line\n";
2279              }              $count++;
2280          }          }
2281            Trace("$count lines put to file $fileName.") if T(File => 3);
2282      }      }
2283      # Return the result.      # Close the output file.
2284      return $retVal;      close $handle;
2285  }  }
2286    
2287  =head3 ParseRecord  =head3 ParseRecord
2288    
2289  C<< my @fields = Tracer::ParseRecord($line); >>      my @fields = Tracer::ParseRecord($line);
2290    
2291  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
2292  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 1508  Line 2331 
2331    
2332  =head3 Merge  =head3 Merge
2333    
2334  C<< my @mergedList = Tracer::Merge(@inputList); >>      my @mergedList = Tracer::Merge(@inputList);
2335    
2336  Sort a list of strings and remove duplicates.  Sort a list of strings and remove duplicates.
2337    
# Line 1554  Line 2377 
2377      return @inputList;      return @inputList;
2378  }  }
2379    
2380  =head3 Percent  =head3 Open
2381    
2382        my $handle = Open($fileHandle, $fileSpec, $message);
2383    
2384    Open a file.
2385    
2386    The I<$fileSpec> is essentially the second argument of the PERL C<open>
2387    function. The mode is specified using Unix-like shell information. So, for
2388    example,
2389    
2390        Open(\*LOGFILE, '>>/usr/spool/news/twitlog', "Could not open twit log.");
2391    
2392    would open for output appended to the specified file, and
2393    
2394        Open(\*DATASTREAM, "| sort -u >$outputFile", "Could not open $outputFile.");
2395    
2396    would open a pipe that sorts the records written and removes duplicates. Note
2397    the use of file handle syntax in the Open call. To use anonymous file handles,
2398    code as follows.
2399    
2400        my $logFile = Open(undef, '>>/usr/spool/news/twitlog', "Could not open twit log.");
2401    
2402    The I<$message> parameter is used if the open fails. If it is set to C<0>, then
2403    the open returns TRUE if successful and FALSE if an error occurred. Otherwise, a
2404    failed open will throw an exception and the third parameter will be used to construct
2405    an error message. If the parameter is omitted, a standard message is constructed
2406    using the file spec.
2407    
2408        Could not open "/usr/spool/news/twitlog"
2409    
2410    Note that the mode characters are automatically cleaned from the file name.
2411    The actual error message from the file system will be captured and appended to the
2412    message in any case.
2413    
2414        Could not open "/usr/spool/news/twitlog": file not found.
2415    
2416    In some versions of PERL the only error message we get is a number, which
2417    corresponds to the C++ C<errno> value.
2418    
2419        Could not open "/usr/spool/news/twitlog": 6.
2420    
2421    =over 4
2422    
2423    =item fileHandle
2424    
2425    File handle. If this parameter is C<undef>, a file handle will be generated
2426    and returned as the value of this method.
2427    
2428    =item fileSpec
2429    
2430    File name and mode, as per the PERL C<open> function.
2431    
2432    =item message (optional)
2433    
2434    Error message to use if the open fails. If omitted, a standard error message
2435    will be generated. In either case, the error information from the file system
2436    is appended to the message. To specify a conditional open that does not throw
2437    an error if it fails, use C<0>.
2438    
2439    =item RETURN
2440    
2441    Returns the name of the file handle assigned to the file, or C<undef> if the
2442    open failed.
2443    
2444    =back
2445    
2446    =cut
2447    
2448    sub Open {
2449        # Get the parameters.
2450        my ($fileHandle, $fileSpec, $message) = @_;
2451        # Attempt to open the file.
2452        my $rv = open $fileHandle, $fileSpec;
2453        # If the open failed, generate an error message.
2454        if (! $rv) {
2455            # Save the system error message.
2456            my $sysMessage = $!;
2457            # See if we need a default message.
2458            if (!$message) {
2459                # Clean any obvious mode characters and leading spaces from the
2460                # filename.
2461                my ($fileName) = FindNamePart($fileSpec);
2462                $message = "Could not open \"$fileName\"";
2463            }
2464            # Terminate with an error using the supplied message and the
2465            # error message from the file system.
2466            Confess("$message: $!");
2467        }
2468        # Return the file handle.
2469        return $fileHandle;
2470    }
2471    
2472    =head3 FindNamePart
2473    
2474        my ($fileName, $start, $len) = Tracer::FindNamePart($fileSpec);
2475    
2476    Extract the portion of a file specification that contains the file name.
2477    
2478    A file specification is the string passed to an C<open> call. It specifies the file
2479    mode and name. In a truly complex situation, it can specify a pipe sequence. This
2480    method assumes that the file name is whatever follows the first angle bracket
2481    sequence.  So, for example, in the following strings the file name is
2482    C</usr/fig/myfile.txt>.
2483    
2484        >>/usr/fig/myfile.txt
2485        </usr/fig/myfile.txt
2486        | sort -u > /usr/fig/myfile.txt
2487    
2488    If the method cannot find a file name using its normal methods, it will return the
2489    whole incoming string.
2490    
2491    =over 4
2492    
2493    =item fileSpec
2494    
2495    File specification string from which the file name is to be extracted.
2496    
2497    =item RETURN
2498    
2499    Returns a three-element list. The first element contains the file name portion of
2500    the specified string, or the whole string if a file name cannot be found via normal
2501    methods. The second element contains the start position of the file name portion and
2502    the third element contains the length.
2503    
2504    =back
2505    
2506    =cut
2507    #: Return Type $;
2508    sub FindNamePart {
2509        # Get the parameters.
2510        my ($fileSpec) = @_;
2511        # Default to the whole input string.
2512        my ($retVal, $pos, $len) = ($fileSpec, 0, length $fileSpec);
2513        # Parse out the file name if we can.
2514        if ($fileSpec =~ m/(<|>>?)(.+?)(\s*)$/) {
2515            $retVal = $2;
2516            $len = length $retVal;
2517            $pos = (length $fileSpec) - (length $3) - $len;
2518        }
2519        # Return the result.
2520        return ($retVal, $pos, $len);
2521    }
2522    
2523    =head3 OpenDir
2524    
2525        my @files = OpenDir($dirName, $filtered, $flag);
2526    
2527    Open a directory and return all the file names. This function essentially performs
2528    the functions of an C<opendir> and C<readdir>. If the I<$filtered> parameter is
2529    set to TRUE, all filenames beginning with a period (C<.>), dollar sign (C<$>),
2530    or pound sign (C<#>) and all filenames ending with a tilde C<~>) will be
2531    filtered out of the return list. If the directory does not open and I<$flag> is not
2532    set, an exception is thrown. So, for example,
2533    
2534        my @files = OpenDir("/Volumes/fig/contigs", 1);
2535    
2536    is effectively the same as
2537    
2538        opendir(TMP, "/Volumes/fig/contigs") || Confess("Could not open /Volumes/fig/contigs.");
2539        my @files = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir(TMP);
2540    
2541    Similarly, the following code
2542    
2543  C<< my $percent = Tracer::Percent($number, $base); >>      my @files = grep { $_ =~ /^\d/ } OpenDir("/Volumes/fig/orgs", 0, 1);
2544    
2545  Returns the percent of the base represented by the given number. If the base  Returns the names of all files in C</Volumes/fig/orgs> that begin with digits and
2546  is zero, returns zero.  automatically returns an empty list if the directory fails to open.
2547    
2548  =over 4  =over 4
2549    
2550  =item number  =item dirName
2551    
2552  Percent numerator.  Name of the directory to open.
2553    
2554  =item base  =item filtered
2555    
2556  Percent base.  TRUE if files whose names begin with a period (C<.>) should be automatically removed
2557    from the list, else FALSE.
2558    
2559  =item RETURN  =item flag
2560    
2561  Returns the percentage of the base represented by the numerator.  TRUE if a failure to open is okay, else FALSE
2562    
2563  =back  =back
2564    
2565  =cut  =cut
2566    #: Return Type @;
2567  sub Percent {  sub OpenDir {
2568      # Get the parameters.      # Get the parameters.
2569      my ($number, $base) = @_;      my ($dirName, $filtered, $flag) = @_;
2570      # Declare the return variable.      # Declare the return variable.
2571      my $retVal = 0;      my @retVal = ();
2572      # Compute the percent.      # Open the directory.
2573      if ($base != 0) {      if (opendir(my $dirHandle, $dirName)) {
2574          $retVal = $number * 100 / $base;          # The directory opened successfully. Get the appropriate list according to the
2575            # strictures of the filter parameter.
2576            if ($filtered) {
2577                @retVal = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir $dirHandle;
2578            } else {
2579                @retVal = readdir $dirHandle;
2580            }
2581            closedir $dirHandle;
2582        } elsif (! $flag) {
2583            # Here the directory would not open and it's considered an error.
2584            Confess("Could not open directory $dirName.");
2585      }      }
2586      # Return the result.      # Return the result.
2587      return $retVal;      return @retVal;
2588  }  }
2589    
 =head3 GetFile  
   
 C<< my @fileContents = Tracer::GetFile($fileName); >>  
2590    
2591      or  =head3 Insure
2592    
2593  C<< my $fileContents = Tracer::GetFile($fileName); >>      Insure($dirName, $chmod);
2594    
2595  Return the entire contents of a file. In list context, line-ends are removed and  Insure a directory is present.
 each line is a list element. In scalar context, line-ends are replaced by C<\n>.  
2596    
2597  =over 4  =over 4
2598    
2599  =item fileName  =item dirName
2600    
2601  Name of the file to read.  Name of the directory to check. If it does not exist, it will be created.
2602    
2603  =item RETURN  =item chmod (optional)
2604    
2605  In a list context, returns the entire file as a list with the line terminators removed.  Security privileges to be given to the directory if it is created.
 In a scalar context, returns the entire file as a string. If an error occurs opening  
 the file, an empty list will be returned.  
2606    
2607  =back  =back
2608    
2609  =cut  =cut
2610    
2611  sub GetFile {  sub Insure {
2612      # Get the parameters.      my ($dirName, $chmod) = @_;
2613      my ($fileName) = @_;      if (! -d $dirName) {
2614      # Declare the return variable.          Trace("Creating $dirName directory.") if T(2);
2615      my @retVal = ();          eval {
2616      # Open the file for input.              mkpath $dirName;
2617      my $handle = Open(undef, "<$fileName");              # If we have permissions specified, set them here.
2618      # Read the whole file into the return variable, stripping off any terminator              if (defined($chmod)) {
2619      # characters.                  chmod $chmod, $dirName;
2620      my $lineCount = 0;              }
2621      while (my $line = <$handle>) {          };
2622          $lineCount++;          if ($@) {
2623          $line = Strip($line);              Confess("Error creating $dirName: $@");
         push @retVal, $line;  
2624      }      }
     # 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;  
     } else {  
         return join "\n", @retVal;  
2625      }      }
2626  }  }
2627    
2628  =head3 PutFile  =head3 ChDir
2629    
2630  C<< Tracer::PutFile($fileName, \@lines); >>      ChDir($dirName);
2631    
2632  Write out a file from a list of lines of text.  Change to the specified directory.
2633    
2634  =over 4  =over 4
2635    
2636  =item fileName  =item dirName
   
 Name of the output file.  
   
 =item lines  
2637    
2638  Reference to a list of text lines. The lines will be written to the file in order, with trailing  Name of the directory to which we want to change.
 new-line characters. Alternatively, may be a string, in which case the string will be written without  
 modification.  
2639    
2640  =back  =back
2641    
2642  =cut  =cut
2643    
2644  sub PutFile {  sub ChDir {
2645      # Get the parameters.      my ($dirName) = @_;
2646      my ($fileName, $lines) = @_;      if (! -d $dirName) {
2647      # Open the output file.          Confess("Cannot change to directory $dirName: no such directory.");
     my $handle = Open(undef, ">$fileName");  
     # Count the lines written.  
     if (ref $lines ne 'ARRAY') {  
         # Here we have a scalar, so we write it raw.  
         print $handle $lines;  
         Trace("Scalar put to file $fileName.") if T(File => 3);  
2648      } else {      } else {
2649          # Write the lines one at a time.          Trace("Changing to directory $dirName.") if T(File => 4);
2650          my $count = 0;          my $okFlag = chdir $dirName;
2651          for my $line (@{$lines}) {          if (! $okFlag) {
2652              print $handle "$line\n";              Confess("Error switching to directory $dirName.");
             $count++;  
2653          }          }
         Trace("$count lines put to file $fileName.") if T(File => 3);  
2654      }      }
     # Close the output file.  
     close $handle;  
2655  }  }
2656    
2657  =head3 QTrace  =head3 SetPermissions
2658    
2659  C<< my $data = QTrace($format); >>      Tracer::SetPermissions($dirName, $group, $mask, %otherMasks);
2660    
2661  Return the queued trace data in the specified format.  Set the permissions for a directory and all the files and folders inside it.
2662    In addition, the group ownership will be changed to the specified value.
2663    
2664    This method is more vulnerable than most to permission and compatability
2665    problems, so it does internal error recovery.
2666    
2667  =over 4  =over 4
2668    
2669  =item format  =item dirName
2670    
2671  C<html> to format the data as an HTML list, C<text> to format it as straight text.  Name of the directory to process.
2672    
2673    =item group
2674    
2675    Name of the group to be assigned.
2676    
2677    =item mask
2678    
2679    Permission mask. Bits that are C<1> in this mask will be ORed into the
2680    permission bits of any file or directory that does not already have them
2681    set to 1.
2682    
2683    =item otherMasks
2684    
2685    Map of search patterns to permission masks. If a directory name matches
2686    one of the patterns, that directory and all its members and subdirectories
2687    will be assigned the new pattern. For example, the following would
2688    assign 0664 to most files, but would use 0777 for directories named C<tmp>.
2689    
2690        Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp$' => 01777);
2691    
2692    The list is ordered, so the following would use 0777 for C<tmp1> and
2693    0666 for C<tmp>, C<tmp2>, or C<tmp3>.
2694    
2695        Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp1' => 0777,
2696                                                       '^tmp' => 0666);
2697    
2698    Note that the pattern matches are all case-insensitive, and only directory
2699    names are matched, not file names.
2700    
2701  =back  =back
2702    
2703  =cut  =cut
2704    
2705  sub QTrace {  sub SetPermissions {
2706      # Get the parameter.      # Get the parameters.
2707      my ($format) = @_;      my ($dirName, $group, $mask, @otherMasks) = @_;
2708      # Create the return variable.      # Set up for error recovery.
2709      my $retVal = "";      eval {
2710      # Only proceed if there is an actual queue.          # Switch to the specified directory.
2711      if (@Queue) {          ChDir($dirName);
2712          # Process according to the format.          # Get the group ID.
2713          if ($format =~ m/^HTML$/i) {          my $gid = getgrnam($group);
2714              # Convert the queue into an HTML list.          # Get the mask for tracing.
2715              $retVal = "<ul>\n";          my $traceMask = sprintf("%04o", $mask) . "($mask)";
2716              for my $line (@Queue) {          Trace("Fixing permissions for directory $dirName using group $group($gid) and mask $traceMask.") if T(File => 2);
2717                  my $escapedLine = CGI::escapeHTML($line);          my $fixCount = 0;
2718                  $retVal .= "<li>$escapedLine</li>\n";          my $lookCount = 0;
2719            # @dirs will be a stack of directories to be processed.
2720            my @dirs = (getcwd());
2721            while (scalar(@dirs) > 0) {
2722                # Get the current directory.
2723                my $dir = pop @dirs;
2724                # Check for a match to one of the specified directory names. To do
2725                # that, we need to pull the individual part of the name off of the
2726                # whole path.
2727                my $simpleName = $dir;
2728                if ($dir =~ m!/([^/]+)$!) {
2729                    $simpleName = $1;
2730                }
2731                Trace("Simple directory name for $dir is $simpleName.") if T(File => 4);
2732                # Search for a match.
2733                my $match = 0;
2734                my $i;
2735                for ($i = 0; $i < $#otherMasks && ! $match; $i += 2) {
2736                    my $pattern = $otherMasks[$i];
2737                    if ($simpleName =~ /$pattern/i) {
2738                        $match = 1;
2739                    }
2740                }
2741                # Find out if we have a match. Note we use $i-1 because the loop added 2
2742                # before terminating due to the match.
2743                if ($match && $otherMasks[$i-1] != $mask) {
2744                    # This directory matches one of the incoming patterns, and it's
2745                    # a different mask, so we process it recursively with that mask.
2746                    SetPermissions($dir, $group, $otherMasks[$i-1], @otherMasks);
2747                } else {
2748                    # Here we can process normally. Get all of the non-hidden members.
2749                    my @submems = OpenDir($dir, 1);
2750                    for my $submem (@submems) {
2751                        # Get the full name.
2752                        my $thisMem = "$dir/$submem";
2753                        Trace("Checking member $thisMem.") if T(4);
2754                        $lookCount++;
2755                        if ($lookCount % 1000 == 0) {
2756                            Trace("$lookCount members examined. Current is $thisMem. Mask is $traceMask") if T(File => 3);
2757                        }
2758                        # Fix the group.
2759                        chown -1, $gid, $thisMem;
2760                        # Insure this member is not a symlink.
2761                        if (! -l $thisMem) {
2762                            # Get its info.
2763                            my $fileInfo = stat $thisMem;
2764                            # Only proceed if we got the info. Otherwise, it's a hard link
2765                            # and we want to skip it anyway.
2766                            if ($fileInfo) {
2767                                my $fileMode = $fileInfo->mode;
2768                                if (($fileMode & $mask) != $mask) {
2769                                    # Fix this member.
2770                                    $fileMode |= $mask;
2771                                    chmod $fileMode, $thisMem;
2772                                    $fixCount++;
2773                                }
2774                                # If it's a subdirectory, stack it.
2775                                if (-d $thisMem) {
2776                                    push @dirs, $thisMem;
2777                                }
2778              }              }
             $retVal .= "</ul>\n";  
         } elsif ($format =~ m/^TEXT$/i) {  
             # Convert the queue into a list of text lines.  
             $retVal = join("\n", @Queue) . "\n";  
2779          }          }
         # Clear the queue.  
         @Queue = ();  
2780      }      }
2781      # Return the formatted list.              }
2782      return $retVal;          }
2783            Trace("$lookCount files and directories processed, $fixCount fixed.") if T(File => 2);
2784        };
2785        # Check for an error.
2786        if ($@) {
2787            Confess("SetPermissions error: $@");
2788        }
2789  }  }
2790    
2791  =head3 Confess  =head3 GetLine
2792    
2793  C<< Confess($message); >>      my @data = Tracer::GetLine($handle);
2794    
2795  Trace the call stack and abort the program with the specified message. When used with  Read a line of data from a tab-delimited file.
 the OR operator and the L</Assert> method, B<Confess> can function as a debugging assert.  
 So, for example  
2796    
2797  C<< Assert($recNum >= 0) || Confess("Invalid record number $recNum."); >>  =over 4
2798    
2799  Will abort the program with a stack trace if the value of C<$recNum> is negative.  =item handle
2800    
2801  =over 4  Open file handle from which to read.
2802    
2803  =item message  =item RETURN
2804    
2805  Message to include in the trace.  Returns a list of the fields in the record read. The fields are presumed to be
2806    tab-delimited. If we are at the end of the file, then an empty list will be
2807    returned. If an empty line is read, a single list item consisting of a null
2808    string will be returned.
2809    
2810  =back  =back
2811    
2812  =cut  =cut
2813    
2814  sub Confess {  sub GetLine {
2815      # Get the parameters.      # Get the parameters.
2816      my ($message) = @_;      my ($handle) = @_;
2817      # Trace the call stack.      # Declare the return variable.
2818      Cluck($message);      my @retVal = ();
2819      # Abort the program.      Trace("File position is " . tell($handle) . ". EOF flag is " . eof($handle) . ".") if T(File => 4);
2820      croak(">>> $message");      # Read from the file.
2821        my $line = <$handle>;
2822        # Only proceed if we found something.
2823        if (defined $line) {
2824            # Remove the new-line. We are a bit over-cautious here because the file may be coming in via an
2825            # upload control and have a nonstandard EOL combination.
2826            $line =~ s/(\r|\n)+$//;
2827            # Here we do some fancy tracing to help in debugging complicated EOL marks.
2828            if (T(File => 4)) {
2829                my $escapedLine = $line;
2830                $escapedLine =~ s/\n/\\n/g;
2831                $escapedLine =~ s/\r/\\r/g;
2832                $escapedLine =~ s/\t/\\t/g;
2833                Trace("Line read: -->$escapedLine<--");
2834  }  }
2835            # If the line is empty, return a single empty string; otherwise, parse
2836  =head3 Assert          # it into fields.
2837            if ($line eq "") {
2838  C<< Assert($condition1, $condition2, ... $conditionN); >>              push @retVal, "";
2839            } else {
2840  Return TRUE if all the conditions are true. This method can be used in conjunction with              push @retVal, split /\t/,$line;
 the OR operator and the L</Confess> method as a debugging assert.  
 So, for example  
   
 C<< Assert($recNum >= 0) || Confess("Invalid record number $recNum."); >>  
   
 Will abort the program with a stack trace if the value of C<$recNum> is negative.  
   
 =cut  
 sub Assert {  
     my $retVal = 1;  
     LOOP: for my $condition (@_) {  
         if (! $condition) {  
             $retVal = 0;  
             last LOOP;  
2841          }          }
2842        } else {
2843            # Trace the reason the read failed.
2844            Trace("End of file: $!") if T(File => 3);
2845      }      }
2846      return $retVal;      # Return the result.
2847        return @retVal;
2848  }  }
2849    
2850  =head3 Cluck  =head3 PutLine
2851    
2852  C<< Cluck($message); >>      Tracer::PutLine($handle, \@fields, $eol);
2853    
2854  Trace the call stack. Note that for best results, you should qualify the call with a  Write a line of data to a tab-delimited file. The specified field values will be
2855  trace condition. For example,  output in tab-separated form, with a trailing new-line.
2856    
2857    =over 4
2858    
2859  C<< Cluck("Starting record parse.") if T(3); >>  =item handle
2860    
2861  will only trace the stack if the trace level for the package is 3 or more.  Output file handle.
2862    
2863  =over 4  =item fields
2864    
2865  =item message  List of field values.
2866    
2867  Message to include in the trace.  =item eol (optional)
2868    
2869    End-of-line character (default is "\n").
2870    
2871  =back  =back
2872    
2873  =cut  =cut
2874    
2875  sub Cluck {  sub PutLine {
2876      # Get the parameters.      # Get the parameters.
2877      my ($message) = @_;      my ($handle, $fields, $eol) = @_;
2878      # Trace what's happening.      # Write the data.
2879      Trace("Stack trace for event: $message");      print $handle join("\t", @{$fields}) . ($eol || "\n");
     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/);  
     }  
2880  }  }
2881    
 =head3 Min  
   
 C<< my $min = Min($value1, $value2, ... $valueN); >>  
2882    
2883  Return the minimum argument. The arguments are treated as numbers.  =head3 PrintLine
2884    
2885  =over 4      Tracer::PrintLine($line);
2886    
2887  =item $value1, $value2, ... $valueN  Print a line of text with a trailing new-line.
2888    
2889  List of numbers to compare.  =over 4
2890    
2891  =item RETURN  =item line
2892    
2893  Returns the lowest number in the list.  Line of text to print.
2894    
2895  =back  =back
2896    
2897  =cut  =cut
2898    
2899  sub Min {  sub PrintLine {
2900      # Get the parameters. Note that we prime the return value with the first parameter.      # Get the parameters.
2901      my ($retVal, @values) = @_;      my ($line) = @_;
2902      # Loop through the remaining parameters, looking for the lowest.      # Print the line.
2903      for my $value (@values) {      print "$line\n";
         if ($value < $retVal) {  
             $retVal = $value;  
         }  
     }  
     # Return the minimum found.  
     return $retVal;  
2904  }  }
2905    
 =head3 Max  
   
 C<< my $max = Max($value1, $value2, ... $valueN); >>  
   
 Return the maximum argument. The arguments are treated as numbers.  
   
 =over 4  
   
 =item $value1, $value2, ... $valueN  
2906    
2907  List of numbers to compare.  =head2 Other Useful Methods
2908    
2909  =item RETURN  =head3 IDHASH
2910    
2911  Returns the highest number in the list.      my $hash = SHTargetSearch::IDHASH(@keys);
2912    
2913  =back  This is a dinky little method that converts a list of values to a reference
2914    to hash of values to labels. The values and labels are the same.
2915    
2916  =cut  =cut
2917    
2918  sub Max {  sub IDHASH {
2919      # Get the parameters. Note that we prime the return value with the first parameter.      my %retVal = map { $_ => $_ } @_;
2920      my ($retVal, @values) = @_;      return \%retVal;
     # Loop through the remaining parameters, looking for the highest.  
     for my $value (@values) {  
         if ($value > $retVal) {  
             $retVal = $value;  
         }  
     }  
     # Return the maximum found.  
     return $retVal;  
2921  }  }
2922    
2923  =head3 AddToListMap  =head3 Pluralize
2924    
2925  C<< Tracer::AddToListMap(\%hash, $key, $value1, $value2, ... valueN); >>      my $plural = Tracer::Pluralize($word);
2926    
2927  Add a key-value pair to a hash of lists. If no value exists for the key, a singleton list  This is a very simple pluralization utility. It adds an C<s> at the end
2928  is created for the key. Otherwise, the new value is pushed onto the list.  of the input word unless it already ends in an C<s>, in which case it
2929    adds C<es>.
2930    
2931  =over 4  =over 4
2932    
2933  =item hash  =item word
   
 Reference to the target hash.  
2934    
2935  =item key  Singular word to pluralize.
2936    
2937  Key for which the value is to be added.  =item RETURN
   
 =item value1, value2, ... valueN  
2938    
2939  List of values to add to the key's value list.  Returns the probable plural form of the word.
2940    
2941  =back  =back
2942    
2943  =cut  =cut
2944    
2945  sub AddToListMap {  sub Pluralize {
2946      # Get the parameters.      # Get the parameters.
2947      my ($hash, $key, @values) = @_;      my ($word) = @_;
     # Process according to whether or not the key already has a value.  
     if (! exists $hash->{$key}) {  
         $hash->{$key} = [@values];  
     } else {  
         push @{$hash->{$key}}, @values;  
     }  
 }  
   
 =head3 DebugMode  
   
 C<< if (Tracer::DebugMode) { ...code... } >>  
   
 Return TRUE if debug mode has been turned on, else abort.  
   
 Certain CGI scripts are too dangerous to exist in the production  
 environment. This method provides a simple way to prevent them  
 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.  
   
 =cut  
   
 sub DebugMode {  
2948      # Declare the return variable.      # Declare the return variable.
2949      my $retVal = 0;      my $retVal;
2950      # Check the debug configuration.      if ($word =~ /s$/) {
2951      my $password = CGI::cookie("DebugMode");          $retVal = $word . 'es';
     my $encrypted = Digest::MD5::md5_hex($password);  
     if ($encrypted eq "252dec43280e0c0d6a75ffcec486e61d") {  
         $retVal = 1;  
2952      } else {      } else {
2953          # Here debug mode is off, so we generate an error.          $retVal = $word . 's';
         Confess("Cannot use this facility without logging in.");  
2954      }      }
2955      # Return the determination indicator.      # Return the result.
2956      return $retVal;      return $retVal;
2957  }  }
2958    
2959  =head3 Strip  =head3 Numeric
2960    
2961  C<< my $string = Tracer::Strip($line); >>      my $okFlag = Tracer::Numeric($string);
2962    
2963  Strip all line terminators off a string. This is necessary when dealing with files  Return the value of the specified string if it is numeric, or an undefined value
2964  that may have been transferred back and forth several times among different  if it is not numeric.
 operating environments.  
2965    
2966  =over 4  =over 4
2967    
2968  =item line  =item string
2969    
2970  Line of text to be stripped.  String to check.
2971    
2972  =item RETURN  =item RETURN
2973    
2974  The same line of text with all the line-ending characters chopped from the end.  Returns the numeric value of the string if successful, or C<undef> if the string
2975    is not numeric.
2976    
2977  =back  =back
2978    
2979  =cut  =cut
2980    
2981  sub Strip {  sub Numeric {
2982      # Get a copy of the parameter string.      # Get the parameters.
2983      my ($string) = @_;      my ($string) = @_;
2984      my $retVal = (defined $string ? $string : "");      # We'll put the value in here if we succeed.
2985      # Strip the line terminator characters.      my $retVal;
2986      $retVal =~ s/(\r|\n)+$//g;      # Get a working copy of the string.
2987        my $copy = $string;
2988        # Trim leading and trailing spaces.
2989        $copy =~ s/^\s+//;
2990        $copy =~ s/\s+$//;
2991        # Check the result.
2992        if ($copy =~ /^[+-]?\d+$/) {
2993            $retVal = $copy;
2994        } elsif ($copy =~ /^([+-]\d+|\d*)[eE][+-]?\d+$/) {
2995            $retVal = $copy;
2996        } elsif ($copy =~ /^([+-]\d+|\d*)\.\d*([eE][+-]?\d+)?$/) {
2997            $retVal = $copy;
2998        }
2999      # Return the result.      # Return the result.
3000      return $retVal;      return $retVal;
3001  }  }
3002    
 =head3 Pad  
3003    
3004  C<< my $paddedString = Tracer::Pad($string, $len, $left, $padChar); >>  =head3 ParseParm
3005    
3006  Pad a string to a specified length. The pad character will be a      my $listValue = Tracer::ParseParm($string);
3007  space, and the padding will be on the right side unless specified  
3008  in the third parameter.  Convert a parameter into a list reference. If the parameter is undefined,
3009    an undefined value will be returned. Otherwise, it will be parsed as a
3010    comma-separated list of values.
3011    
3012  =over 4  =over 4
3013    
3014  =item string  =item string
3015    
3016  String to be padded.  Incoming string.
   
 =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.  
3017    
3018  =item RETURN  =item RETURN
3019    
3020  Returns a copy of the original string with the pad character added to the  Returns a reference to a list of values, or C<undef> if the incoming value
3021  specified end so that it achieves the desired length.  was undefined.
3022    
3023  =back  =back
3024    
3025  =cut  =cut
3026    
3027  sub Pad {  sub ParseParm {
3028      # Get the parameters.      # Get the parameters.
3029      my ($string, $len, $left, $padChar) = @_;      my ($string) = @_;
3030      # Compute the padding character.      # Declare the return variable.
3031      if (! defined $padChar) {      my $retVal;
3032          $padChar = " ";      # Check for data.
3033      }      if (defined $string) {
3034      # Compute the number of spaces needed.          # We have some, so split it into a list.
3035      my $needed = $len - length $string;          $retVal = [ split /\s*,\s*/, $string];
     # Copy the string into the return variable.  
     my $retVal = $string;  
     # Only proceed if padding is needed.  
     if ($needed > 0) {  
         # Create the pad string.  
         my $pad = $padChar x $needed;  
         # Affix it to the return value.  
         if ($left) {  
             $retVal = $pad . $retVal;  
         } else {  
             $retVal .= $pad;  
         }  
3036      }      }
3037      # Return the result.      # Return the result.
3038      return $retVal;      return $retVal;
3039  }  }
3040    
3041  =head3 EOF  =head3 Now
3042    
3043  This is a constant that is lexically greater than any useful string.      my $string = Tracer::Now();
3044    
3045    Return a displayable time stamp containing the local time. Whatever format this
3046    method produces must be parseable by L</ParseDate>.
3047    
3048  =cut  =cut
3049    
3050  sub EOF {  sub Now {
3051      return "\xFF\xFF\xFF\xFF\xFF";      return DisplayTime(time);
3052  }  }
3053    
3054  =head3 TICK  =head3 DisplayTime
   
 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`  
   
 from inside a CGI script, it would work fine in Unix, but would issue an error message  
 in Windows complaining that C<'.'> is not a valid command. If instead you code  
3055    
3056      TICK("./protein.cgi")      my $string = Tracer::DisplayTime($time);
3057    
3058  it will work correctly in both environments.  Convert a time value to a displayable time stamp. Whatever format this
3059    method produces must be parseable by L</ParseDate>.
3060    
3061  =over 4  =over 4
3062    
3063  =item commandString  =item time
3064    
3065  The command string to pass to the system.  Time to display, in seconds since the epoch, or C<undef> if the time is unknown.
3066    
3067  =item RETURN  =item RETURN
3068    
3069  Returns the standard output from the specified command, as a list.  Returns a displayable time, or C<(n/a)> if the incoming time is undefined.
3070    
3071  =back  =back
3072    
3073  =cut  =cut
3074  #: Return Type @;  
3075  sub TICK {  sub DisplayTime {
3076      # Get the parameters.      my ($time) = @_;
3077      my ($commandString) = @_;      my $retVal = "(n/a)";
3078      # Chop off the dot-slash if this is Windows.      if (defined $time) {
3079      if ($FIG_Config::win_mode) {          my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time);
3080          $commandString =~ s!^\./!!;          $retVal = _p2($mon+1) . "/" . _p2($mday) . "/" . ($year + 1900) . " " .
3081                      _p2($hour) . ":" . _p2($min) . ":" . _p2($sec);
3082      }      }
3083      # Activate the command and return the result.      return $retVal;
     return `$commandString`;  
3084  }  }
3085    
3086  =head3 ScriptSetup  # Pad a number to 2 digits.
3087    sub _p2 {
3088  C<< my ($cgi, $varHash) = ScriptSetup($noTrace); >>      my ($value) = @_;
3089        $value = "0$value" if ($value < 10);
3090        return $value;
3091    }
3092    
3093  Perform standard tracing and debugging setup for scripts. The value returned is  =head3 Escape
 the CGI object followed by a pre-built variable hash.  
3094    
3095  The C<Trace> form parameter is used to determine whether or not tracing is active and      my $codedString = Tracer::Escape($realString);
 which trace modules (other than C<Tracer> itself) should be turned on. Specifying  
 the C<CGI> trace module will trace parameter and environment information. Parameters are  
 traced at level 3 and environment variables at level 4. To trace to a file instead of to  
 the web page, set C<TF> to 1. At the end of the script, the client should call  
 L</ScriptFinish> to output the web page.  
3096    
3097  In some situations, it is not practical to invoke tracing via form parameters. For this  Escape a string for use in a command. Tabs will be replaced by C<\t>, new-lines
3098  situation, you can turn on emergency tracing from the debugging control panel.  replaced by C<\n>, carriage returns will be deleted, and backslashes will be doubled. The
3099  Tracing will then be turned on automatically for all programs that use the L</ETracing>  result is to reverse the effect of L</UnEscape>.
 method, which includes every program that uses this method or L</StandardSetup>.  
3100    
3101  =over 4  =over 4
3102    
3103  =item noTrace (optional)  =item realString
3104    
3105  If specified, tracing will be suppressed. This is useful if the script wants to set up  String to escape.
 tracing manually.  
3106    
3107  =item RETURN  =item RETURN
3108    
3109  Returns a two-element list consisting of a CGI query object and a variable hash for  Escaped equivalent of the real string.
 the output page.  
3110    
3111  =back  =back
3112    
3113  =cut  =cut
3114    
3115  sub ScriptSetup {  sub Escape {
3116      # Get the parameters.      # Get the parameter.
3117      my ($noTrace) = @_;      my ($realString) = @_;
3118      # Get the CGI query object.      # Initialize the return variable.
3119      my $cgi = CGI->new();      my $retVal = "";
3120      # Set up tracing if it's not suppressed.      # Loop through the parameter string, looking for sequences to escape.
3121      ETracing($cgi) unless $noTrace;      while (length $realString > 0) {
3122      # Create the variable hash.          # Look for the first sequence to escape.
3123      my $varHash = { results => '' };          if ($realString =~ /^(.*?)([\n\t\r\\])/) {
3124      # Return the query object and variable hash.              # Here we found it. The text preceding the sequence is in $1. The sequence
3125      return ($cgi, $varHash);              # itself is in $2. First, move the clear text to the return variable.
3126                $retVal .= $1;
3127                # Strip the processed section off the real string.
3128                $realString = substr $realString, (length $2) + (length $1);
3129                # Get the matched character.
3130                my $char = $2;
3131                # If we have a CR, we are done.
3132                if ($char ne "\r") {
3133                    # It's not a CR, so encode the escape sequence.
3134                    $char =~ tr/\t\n/tn/;
3135                    $retVal .= "\\" . $char;
3136                }
3137            } else {
3138                # Here there are no more escape sequences. The rest of the string is
3139                # transferred unmodified.
3140                $retVal .= $realString;
3141                $realString = "";
3142            }
3143        }
3144        # Return the result.
3145        return $retVal;
3146  }  }
3147    
3148  =head3 ETracing  =head3 UnEscape
3149    
3150  C<< ETracing($parameter); >>      my $realString = Tracer::UnEscape($codedString);
3151    
3152  Set up emergency tracing. Emergency tracing is tracing that is turned  Replace escape sequences with their actual equivalents. C<\t> will be replaced by
3153  on automatically for any program that calls this method. The emergency  a tab, C<\n> by a new-line character, and C<\\> by a backslash. C<\r> codes will
3154  tracing parameters are stored in a a file identified by a tracing key.  be deleted.
 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.  
3155    
3156  =over 4  =over 4
3157    
3158  =item parameter  =item codedString
3159    
3160  A parameter from which the tracing key is computed. If it is a scalar,  String to un-escape.
3161  that scalar is used as the tracing key. If it is a CGI object, the  
3162  tracing key is taken from the C<IP> cookie. If it is omitted, the  =item RETURN
3163  tracing key is taken from the C<TRACING> environment variable. If it  
3164  is a CGI object and emergency tracing is not on, the C<Trace> and  Returns a copy of the original string with the escape sequences converted to their actual
3165  C<TF> parameters will be used to determine the type of tracing.  values.
3166    
3167  =back  =back
3168    
3169  =cut  =cut
3170    
3171  sub ETracing {  sub UnEscape {
3172      # Get the parameter.      # Get the parameter.
3173      my ($parameter) = @_;      my ($codedString) = @_;
3174      # Check for CGI mode.      # Initialize the return variable.
3175      my $cgi = (ref $parameter eq 'CGI' ? $parameter : undef);      my $retVal = "";
3176      # Default to no tracing except errors.      # Only proceed if the incoming string is nonempty.
3177      my ($tracing, $dest) = ("0", "WARN");      if (defined $codedString) {
3178      # Check for emergency tracing.          # Loop through the parameter string, looking for escape sequences. We can't do
3179      my $tkey = EmergencyKey($parameter);          # translating because it causes problems with the escaped slash. ("\\t" becomes
3180      my $emergencyFile = EmergencyFileName($tkey);          # "\<tab>" no matter what we do.)
3181      if (-e $emergencyFile) {          while (length $codedString > 0) {
3182          # We have the file. Read in the data.              # Look for the first escape sequence.
3183          my @tracing = GetFile($emergencyFile);              if ($codedString =~ /^(.*?)\\(\\|n|t|r)/) {
3184          # Pull off the time limit.                  # Here we found it. The text preceding the sequence is in $1. The sequence
3185          my $expire = shift @tracing;                  # itself is in $2. First, move the clear text to the return variable.
3186          # Convert it to seconds.                  $retVal .= $1;
3187          $expire *= 3600;                  $codedString = substr $codedString, (2 + length $1);
3188          # Check the file data.                  # Get the escape value.
3189          my $stat = stat($emergencyFile);                  my $char = $2;
3190          my ($now) = gettimeofday;                  # If we have a "\r", we are done.
3191          if ($now - $stat->mtime > $expire) {                  if ($char ne 'r') {
3192              # Delete the expired file.                      # Here it's not an 'r', so we convert it.
3193              unlink $emergencyFile;                      $char =~ tr/\\tn/\\\t\n/;
3194          } else {                      $retVal .= $char;
             # 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);  
3195          }          }
3196      } elsif (defined $cgi) {              } else {
3197          # There's no emergency tracing, but we have a CGI object, so check                  # Here there are no more escape sequences. The rest of the string is
3198          # for tracing from the form parameters.                  # transferred unmodified.
3199          if ($cgi->param('Trace')) {                  $retVal .= $codedString;
3200              # Here the user has requested tracing via a form.                  $codedString = "";
             $dest = ($cgi->param('TF') ? ">$FIG_Config::temp/Trace$$.log" : "QUEUE");  
             $tracing = $cgi->param('Trace') . " Tracer";  
3201          }          }
3202      }      }
     # Setup the tracing we've determined from all the stuff above.  
     TSetup($tracing, $dest);  
     # If we're a web script, trace the parameter and environment data.  
     if (defined $cgi) {  
         TraceParms($cgi);  
3203      }      }
3204        # Return the result.
3205        return $retVal;
3206  }  }
3207    
3208  =head3 EmergencyFileName  =head3 Percent
3209    
3210  C<< my $fileName = Tracer::EmergencyFileName($tkey); >>      my $percent = Tracer::Percent($number, $base);
3211    
3212  Return the emergency tracing file name. This is the file that specifies  Returns the percent of the base represented by the given number. If the base
3213  the tracing information.  is zero, returns zero.
3214    
3215  =over 4  =over 4
3216    
3217  =item tkey  =item number
3218    
3219  Tracing key for the current program.  Percent numerator.
3220    
3221    =item base
3222    
3223    Percent base.
3224    
3225  =item RETURN  =item RETURN
3226    
3227  Returns the name of the file to contain the emergency tracing information.  Returns the percentage of the base represented by the numerator.
3228    
3229  =back  =back
3230    
3231  =cut  =cut
3232    
3233  sub EmergencyFileName {  sub Percent {
3234      # Get the parameters.      # Get the parameters.
3235      my ($tkey) = @_;      my ($number, $base) = @_;
3236      # Compute the emergency tracing file name.      # Declare the return variable.
3237      return "$FIG_Config::temp/Emergency$tkey.txt";      my $retVal = 0;
3238        # Compute the percent.
3239        if ($base != 0) {
3240            $retVal = $number * 100 / $base;
3241        }
3242        # Return the result.
3243        return $retVal;
3244  }  }
3245    
3246  =head3 EmergencyFileTarget  =head3 In
   
 C<< my $fileName = Tracer::EmergencyFileTarget($tkey); >>  
   
 Return the emergency tracing target file name. This is the file that receives  
 the tracing output for file-based tracing.  
   
 =over 4  
   
 =item tkey  
   
 Tracing key for the current program.  
   
 =item RETURN  
3247    
3248  Returns the name of the file to contain the trace output.      my $flag = Tracer::In($value, $min, $max);
3249    
3250  =back  Return TRUE if the value is between the minimum and the maximum, else FALSE.
3251    
3252  =cut  =cut
3253    
3254  sub EmergencyFileTarget {  sub In {
3255      # Get the parameters.      return ($_[0] <= $_[2] && $_[0] >= $_[1]);
     my ($tkey) = @_;  
     # Compute the emergency tracing file name.  
     return "$FIG_Config::temp/trace$tkey.log";  
3256  }  }
3257    
 =head3 EmergencyTracingDest  
3258    
3259  C<< my $dest = Tracer::EmergencyTracingDest($tkey, $myDest); >>  =head3 Constrain
3260    
3261  This method converts an emergency tracing destination to a real      my $constrained = Constrain($value, $min, $max);
3262  tracing destination. The main difference is that if the  
3263  destination is C<FILE> or C<APPEND>, we convert it to file  Modify a numeric value to bring it to a point in between a maximum and a minimum.
 output.  
3264    
3265  =over 4  =over 4
3266    
3267  =item tkey  =item value
3268    
3269  Tracing key for this environment.  Value to constrain.
3270    
3271  =item myDest  =item min (optional)
3272    
3273  Destination from the emergency tracing file.  Minimum permissible value. If this parameter is undefined, no minimum constraint will be applied.
3274    
3275    =item max (optional)
3276    
3277    Maximum permissible value. If this parameter is undefined, no maximum constraint will be applied.
3278    
3279  =item RETURN  =item RETURN
3280    
3281  Returns a destination that can be passed into L</TSetup>.  Returns the incoming value, constrained according to the other parameters.
3282    
3283  =back  =back
3284    
3285  =cut  =cut
3286    
3287  sub EmergencyTracingDest {  sub Constrain {
3288      # Get the parameters.      # Get the parameters.
3289      my ($tkey, $myDest) = @_;      my ($value, $min, $max) = @_;
3290      # Declare the return variable.      # Declare the return variable.
3291      my $retVal;      my $retVal = $value;
3292      # Process according to the destination value.      # Apply the minimum constraint.
3293      if ($myDest eq 'FILE') {      if (defined $min && $retVal < $min) {
3294          $retVal = ">" . EmergencyFileTarget($tkey);          $retVal = $min;
3295      } elsif ($myDest eq 'APPEND') {      }
3296          $retVal = ">>" . EmergencyFileTarget($tkey);      # Apply the maximum constraint.
3297      } else {      if (defined $max && $retVal > $max) {
3298          $retVal = $myDest;          $retVal = $max;
3299      }      }
3300      # Return the result.      # Return the result.
3301      return $retVal;      return $retVal;
3302  }  }
3303    
3304  =head3 Emergency  =head3 Min
3305    
3306  C<< Emergency($key, $hours, $dest, $level, @modules); >>      my $min = Min($value1, $value2, ... $valueN);
3307    
3308  Turn on emergency tracing. This method can only be invoked over the web and is  Return the minimum argument. The arguments are treated as numbers.
 should not be called if debug mode is off. 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.  
3309    
3310  =over 4  =over 4
3311    
3312  =item tkey  =item $value1, $value2, ... $valueN
   
 The tracing key. This is used to identify the control file and the trace file.  
   
 =item hours  
   
 Number of hours to keep emergency tracing alive.  
   
 =item dest  
   
 Tracing destination. If no path information is specified for a file  
 destination, it is put in the FIG temporary directory.  
   
 =item level  
3313    
3314  Tracing level. A higher level means more trace messages.  List of numbers to compare.
3315    
3316  =item modules  =item RETURN
3317    
3318  A list of the tracing modules to activate.  Returns the lowest number in the list.
3319    
3320  =back  =back
3321    
3322  =cut  =cut
3323    
3324  sub Emergency {  sub Min {
3325      # Get the parameters.      # Get the parameters. Note that we prime the return value with the first parameter.
3326      my ($tkey, $hours, $dest, $level, @modules) = @_;      my ($retVal, @values) = @_;
3327      # Create the emergency file.      # Loop through the remaining parameters, looking for the lowest.
3328      my $specFile = EmergencyFileName($tkey);      for my $value (@values) {
3329      my $outHandle = Open(undef, ">$specFile");          if ($value < $retVal) {
3330      print $outHandle join("\n", $hours, $dest, $level, @modules, "");              $retVal = $value;
3331            }
3332        }
3333        # Return the minimum found.
3334        return $retVal;
3335  }  }
3336    
3337  =head3 EmergencyKey  =head3 Max
3338    
3339  C<< my $tkey = EmergencyKey($parameter); >>      my $max = Max($value1, $value2, ... $valueN);
3340    
3341  Return the Key to be used for emergency tracing. This could be an IP address,  Return the maximum argument. The arguments are treated as numbers.
  a session ID, or a user name, depending on the environment.  
3342    
3343  =over 4  =over 4
3344    
3345  =item parameter  =item $value1, $value2, ... $valueN
3346    
3347  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.  
3348    
3349  =item RETURN  =item RETURN
3350    
3351  Returns the key to be used for labels in emergency tracing.  Returns the highest number in the list.
3352    
3353  =back  =back
3354    
3355  =cut  =cut
3356    
3357  sub EmergencyKey {  sub Max {
3358      # Get the parameters.      # Get the parameters. Note that we prime the return value with the first parameter.
3359      my ($parameter) = @_;      my ($retVal, @values) = @_;
3360      # Declare the return variable.      # Loop through the remaining parameters, looking for the highest.
3361      my $retVal;      for my $value (@values) {
3362      # Determine the parameter type.          if ($value > $retVal) {
3363      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;  
         }  
3364      }      }
     # If no luck finding a key, use the PID.  
     if (! defined $retVal) {  
         $retVal = $$;  
3365      }      }
3366      # Return the result.      # Return the maximum found.
3367      return $retVal;      return $retVal;
3368  }  }
3369    
3370    =head3 Strip
3371    
3372  =head3 TraceParms      my $string = Tracer::Strip($line);
   
 C<< Tracer::TraceParms($cgi); >>  
3373    
3374  Trace the CGI parameters at trace level CGI => 3 and the environment variables  Strip all line terminators off a string. This is necessary when dealing with files
3375  at level CGI => 4.  that may have been transferred back and forth several times among different
3376    operating environments.
3377    
3378  =over 4  =over 4
3379    
3380  =item cgi  =item line
3381    
3382  CGI query object containing the parameters to trace.  Line of text to be stripped.
3383    
3384    =item RETURN
3385    
3386    The same line of text with all the line-ending characters chopped from the end.
3387    
3388  =back  =back
3389    
3390  =cut  =cut
3391    
3392  sub TraceParms {  sub Strip {
3393      # Get the parameters.      # Get a copy of the parameter string.
3394      my ($cgi) = @_;      my ($string) = @_;
3395      if (T(CGI => 3)) {      my $retVal = (defined $string ? $string : "");
3396          # Here we want to trace the parameter data.      # Strip the line terminator characters.
3397          my @names = $cgi->param;      $retVal =~ s/(\r|\n)+$//g;
3398          for my $parmName (sort @names) {      # Return the result.
3399              # Note we skip the Trace parameters, which are for our use only.      return $retVal;
             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}");  
         }  
     }  
3400  }  }
3401    
3402  =head3 ScriptFinish  =head3 Trim
   
 C<< ScriptFinish($webData, $varHash); >>  
   
 Output a web page at the end of a script. Either the string to be output or the  
 name of a template file can be specified. If the second parameter is omitted,  
 it is assumed we have a string to be output; otherwise, it is assumed we have the  
 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.  
   
 A typical standard script would loook like the following.  
   
     BEGIN {  
         # Print the HTML header.  
         print "CONTENT-TYPE: text/html\n\n";  
     }  
     use Tracer;  
     use CGI;  
     use FIG;  
     # ... more uses ...  
3403    
3404      my ($cgi, $varHash) = ScriptSetup();      my $string = Tracer::Trim($line);
     eval {  
         # ... get data from $cgi, put it in $varHash ...  
     };  
     if ($@) {  
         Trace("Script Error: $@") if T(0);  
     }  
     ScriptFinish("Html/MyTemplate.html", $varHash);  
3405    
3406  The idea here is that even if the script fails, you'll see trace messages and  Trim all spaces from the beginning and ending of a string.
 useful output.  
3407    
3408  =over 4  =over 4
3409    
3410  =item webData  =item line
3411    
3412  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.  
3413    
3414  =item varHash (optional)  =item RETURN
3415    
3416  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.  
3417    
3418  =back  =back
3419    
3420  =cut  =cut
3421    
3422  sub ScriptFinish {  sub Trim {
3423      # Get the parameters.      # Get a copy of the parameter string.
3424      my ($webData, $varHash) = @_;      my ($string) = @_;
3425      # Check for a template file situation.      my $retVal = (defined $string ? $string : "");
3426      my $outputString;      # Strip the front spaces.
3427      if (defined $varHash) {      $retVal =~ s/^\s+//;
3428          # Here we have a template file. We need to determine the template type.      # Strip the back spaces.
3429          my $template;      $retVal =~ s/\s+$//;
3430          if ($FIG_Config::template_url && $webData =~ /\.php$/) {      # Return the result.
3431              $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;  
3432  }  }
3433    
3434  =head3 Insure  =head3 Pad
3435    
3436  C<< Insure($dirName); >>      my $paddedString = Tracer::Pad($string, $len, $left, $padChar);
3437    
3438  Insure a directory is present.  Pad a string to a specified length. The pad character will be a
3439    space, and the padding will be on the right side unless specified
3440    in the third parameter.
3441    
3442  =over 4  =over 4
3443    
3444  =item dirName  =item string
3445    
3446  Name of the directory to check. If it does not exist, it will be created.  String to be padded.
3447    
3448    =item len
3449    
3450    Desired length of the padded string.
3451    
3452    =item left (optional)
3453    
3454    TRUE if the string is to be left-padded; otherwise it will be padded on the right.
3455    
3456    =item padChar (optional)
3457    
3458    Character to use for padding. The default is a space.
3459    
3460    =item RETURN
3461    
3462    Returns a copy of the original string with the pad character added to the
3463    specified end so that it achieves the desired length.
3464    
3465  =back  =back
3466    
3467  =cut  =cut
3468    
3469  sub Insure {  sub Pad {
3470      my ($dirName) = @_;      # Get the parameters.
3471      if (! -d $dirName) {      my ($string, $len, $left, $padChar) = @_;
3472          Trace("Creating $dirName directory.") if T(File => 2);      # Compute the padding character.
3473          eval { mkpath $dirName; };      if (! defined $padChar) {
3474          if ($@) {          $padChar = " ";
3475              Confess("Error creating $dirName: $@");      }
3476        # Compute the number of spaces needed.
3477        my $needed = $len - length $string;
3478        # Copy the string into the return variable.
3479        my $retVal = $string;
3480        # Only proceed if padding is needed.
3481        if ($needed > 0) {
3482            # Create the pad string.
3483            my $pad = $padChar x $needed;
3484            # Affix it to the return value.
3485            if ($left) {
3486                $retVal = $pad . $retVal;
3487            } else {
3488                $retVal .= $pad;
3489          }          }
3490      }      }
3491        # Return the result.
3492        return $retVal;
3493  }  }
3494    
3495  =head3 ChDir  =head3 Quoted
3496    
3497  C<< ChDir($dirName); >>      my $string = Tracer::Quoted($var);
3498    
3499  Change to the specified directory.  Convert the specified value to a string and enclose it in single quotes.
3500    If it's undefined, the string C<undef> in angle brackets will be used
3501    instead.
3502    
3503  =over 4  =over 4
3504    
3505  =item dirName  =item var
3506    
3507  Name of the directory to which we want to change.  Value to quote.
3508    
3509    =item RETURN
3510    
3511    Returns a string enclosed in quotes, or an indication the value is undefined.
3512    
3513  =back  =back
3514    
3515  =cut  =cut
3516    
3517  sub ChDir {  sub Quoted {
3518      my ($dirName) = @_;      # Get the parameters.
3519      if (! -d $dirName) {      my ($var) = @_;
3520          Confess("Cannot change to directory $dirName: no such directory.");      # Declare the return variable.
3521        my $retVal;
3522        # Are we undefined?
3523        if (! defined $var) {
3524            $retVal = "<undef>";
3525      } else {      } else {
3526          Trace("Changing to directory $dirName.") if T(File => 4);          # No, so convert to a string and enclose in quotes.
3527          my $okFlag = chdir $dirName;          $retVal = $var;
3528          if (! $okFlag) {          $retVal =~ s/'/\\'/;
3529              Confess("Error switching to directory $dirName.");          $retVal = "'$retVal'";
         }  
3530      }      }
3531        # Return the result.
3532        return $retVal;
3533  }  }
3534    
3535  =head3 SendSMS  =head3 EOF
3536    
3537  C<< my $msgID = Tracer::SendSMS($phoneNumber, $msg); >>  This is a constant that is lexically greater than any useful string.
3538    
3539  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  
3540    
3541      $phone =  { user => 'BruceTheHumanPet',  sub EOF {
3542                  password => 'silly',      return "\xFF\xFF\xFF\xFF\xFF";
3543                  api_id => '2561022' };  }
3544    
3545  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.  
3546    
3547  The message ID will be returned if successful, and C<undef> if an error occurs.      my @results = TICK($commandString);
3548    
3549  =over 4  Perform a back-tick operation on a command. If this is a Windows environment, any leading
3550    dot-slash (C<./> will be removed. So, for example, if you were doing
3551    
3552  =item phoneNumber      `./protein.cgi`
3553    
3554  Phone number to receive the message, in international format. A United States phone number  from inside a CGI script, it would work fine in Unix, but would issue an error message
3555  would be prefixed by "1". A British phone number would be prefixed by "44".  in Windows complaining that C<'.'> is not a valid command. If instead you code
3556    
3557  =item msg      TICK("./protein.cgi")
3558    
3559  Message to send to the specified phone.  it will work correctly in both environments.