[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.61, Fri Jul 28 02:03:04 2006 UTC revision 1.124, Thu Aug 27 19:47:14 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 ScriptSetup ScriptFinish Insure ChDir);  
     @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 32  Line 33 
33      use File::Path;      use File::Path;
34      use File::stat;      use File::stat;
35      use LWP::UserAgent;      use LWP::UserAgent;
36        use Time::HiRes 'gettimeofday';
37        use URI::Escape;
38        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    
47  =head2 Introduction  =head2 Tracing
48    
49  This package provides simple tracing for debugging and reporting purposes. To use it simply call the  This package provides simple tracing for debugging and reporting purposes. To use it simply call the
50  L</TSetup> method to set the options and call L</Trace> to write out trace messages. Each trace  L</TSetup> or L</ETracing> method to set the options and call L</Trace> to write out trace messages.
51  message has a I<trace level> and I<category> associated with it. In addition, the tracing package itself  L</TSetup> and L</ETracing> both establish a I<trace level> and a list of I<categories>. Similarly,
52  has a list of categories and a single trace level set by the B<TSetup> method. Only messages whose trace  each trace message has a I<trace level> and I<category> associated with it. Only messages whose trace
53  level is less than or equal to this package's trace level and whose category is activated will  level is less than or equal to the setup trace level and whose category is activated will
54  be written. Thus, a higher trace level on a message indicates that the message  be written. Thus, a higher trace level on a message indicates that the message
55  is less likely to be seen. A higher trace level passed to B<TSetup> means more trace messages will  is less likely to be seen, while a higher trace level passed to B<TSetup> means more trace messages will
56  appear. To generate a trace message, use the following syntax.  appear.
57    
58    =head3 Putting Trace Messages in Your Code
59    
60  C<< Trace($message) if T(errors => 4); >>  To generate a trace message, use the following syntax.
61    
62        Trace($message) if T(errors => 4);
63    
64  This statement will produce a trace message if the trace level is 4 or more and the C<errors>  This statement will produce a trace message if the trace level is 4 or more and the C<errors>
65  category is active. Note that the special category C<main> is always active, so  category is active. There is a special category C<main> that is always active, so
66    
67  C<< Trace($message) if T(main => 4); >>      Trace($message) if T(main => 4);
68    
69  will trace if the trace level is 4 or more.  will trace if the trace level is 4 or more.
70    
# Line 59  Line 72 
72  following call is made in the B<Sprout> package, it will appear if the C<Sprout> category is  following call is made in the B<Sprout> package, it will appear if the C<Sprout> category is
73  active and the trace level is 2 or more.  active and the trace level is 2 or more.
74    
75  C<< Trace($message) if T(2); >>      Trace($message) if T(2);
76    
77    In scripts, where no package name is available, the category defaults to C<main>.
78    
79    =head3 Custom Tracing
80    
81    Many programs have customized tracing configured using the L</TSetup> method. This is no longer
82    the preferred method, but a knowledge of how custom tracing works can make the more modern
83    L</Emergency Tracing> easier to understand.
84    
85  To set up tracing, you call the L</TSetup> method. The method takes as input a trace level, a list  To set up custom tracing, you call the L</TSetup> method. The method takes as input a trace level,
86  of category names, and a set of options. The trace level and list of category names are  a list of category names, and a destination. The trace level and list of category names are
87  specified as a space-delimited string. Thus  specified as a space-delimited string. Thus
88    
89  C<< TSetup('3 errors Sprout ERDB', 'HTML'); >>      TSetup('3 errors Sprout ERDB', 'TEXT');
90    
91  sets the trace level to 3, activates the C<errors>, C<Sprout>, and C<ERDB> categories, and  sets the trace level to 3, activates the C<errors>, C<Sprout>, and C<ERDB> categories, and
92  specifies that messages should be output as HTML paragraphs.  specifies that messages should be sent to the standard output.
93    
94  To turn on tracing for ALL categories, use an asterisk. The call below sets every category to  To turn on tracing for ALL categories, use an asterisk. The call below sets every category to
95  level 3 and writes the output to the standard error output. This sort of thing might be  level 3 and writes the output to the standard error output. This sort of thing might be
96  useful in a CGI environment.  useful in a CGI environment.
97    
98  C<< TSetup('3 *', 'WARN'); >>      TSetup('3 *', 'WARN');
99    
100  In addition to HTML and file output for trace messages, you can specify that the trace messages  In addition standard error and file output for trace messages, you can specify that the trace messages
101  be queued. The messages can then be retrieved by calling the L</QTrace> method. This approach  be queued. The messages can then be retrieved by calling the L</QTrace> method. This approach
102  is useful if you are building a web page. Instead of having the trace messages interspersed with  is useful if you are building a web page. Instead of having the trace messages interspersed with
103  the page output, they can be gathered together and displayed at the end of the page. This makes  the page output, they can be gathered together and displayed at the end of the page. This makes
104  it easier to debug page formatting problems.  it easier to debug page formatting problems.
105    
106  Finally, you can specify that all trace messages be emitted as warnings.  Finally, you can specify that all trace messages be emitted to a file, or the standard output and
107    a file at the same time. To trace to a file, specify the filename with an output character in front
108    of it.
109    
110        TSetup('4 SQL', ">$fileName");
111    
112    To trace to the standard output and a file at the same time, put a C<+> in front of the angle
113    bracket.
114    
115        TSetup('3 *', "+>$fileName");
116    
117  The flexibility of tracing makes it superior to simple use of directives like C<die> and C<warn>.  The flexibility of tracing makes it superior to simple use of directives like C<die> and C<warn>.
118  Tracer calls can be left in the code with minimal overhead and then turned on only when needed.  Tracer calls can be left in the code with minimal overhead and then turned on only when needed.
119  Thus, debugging information is available and easily retrieved even when the application is  Thus, debugging information is available and easily retrieved even when the application is
120  being used out in the field.  being used out in the field.
121    
122    =head3 Trace Levels
123    
124  There is no hard and fast rule on how to use trace levels. The following is therefore only  There is no hard and fast rule on how to use trace levels. The following is therefore only
125  a suggestion.  a suggestion.
126    
# Line 119  Line 151 
151    
152  =back  =back
153    
154    The format of trace messages is important because some utilities analyze trace files.
155    There are three fields-- the time stamp, the category name, and the text.
156    The time stamp is between square brackets and the category name between angle brackets.
157    After the category name there is a colon (C<:>) followed by the message text.
158    If the square brackets or angle brackets are missing, then the trace management
159    utilities assume that they are encountering a set of pre-formatted lines.
160    
161    Note, however, that this formatting is done automatically by the tracing functions. You
162    only need to know about it if you want to parse a trace file.
163    
164    =head3 Emergency Tracing
165    
166    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
168    from the debug form, which is accessed from the [[DebugConsole]]. Emergency tracing requires
169    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
171    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.
173    
174    The key can be anything you want. If you don't have a key, the C<SetPassword> page will
175    generate one for you.
176    
177    You can activate and de-activate emergency tracing from the debugging control panel, as
178    well as display the trace file itself.
179    
180    To enable emergency tracing in your code, call
181    
182        ETracing($cgi)
183    
184    from a web script and
185    
186        ETracing()
187    
188    from a command-line script.
189    
190    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
192    using the L</StandardSetup> method or a [[WebApplication]], emergency tracing
193    will be configured automatically.
194    
195  =cut  =cut
196    
197  # Declare the configuration variables.  # Declare the configuration variables.
198    
199  my $Destination = "NONE";   # Description of where to send the trace output.  my $Destination = "WARN";   # Description of where to send the trace output.
200  my $TeeFlag = 0;            # TRUE if output is going to a file and to the  my $TeeFlag = 0;            # TRUE if output is going to a file and to the
201                              # standard output                              # standard output
202  my %Categories = ( main => 1 );  my %Categories = ( main => 1 );
203                              # hash of active category names                              # hash of active category names
204    my @LevelNames = qw(error warn notice info detail);
205  my $TraceLevel = 0;         # trace level; a higher trace level produces more  my $TraceLevel = 0;         # trace level; a higher trace level produces more
206                              # messages                              # messages
207  my @Queue = ();             # queued list of trace messages.  my @Queue = ();             # queued list of trace messages.
208  my $LastCategory = "main";  # name of the last category interrogated  my $LastCategory = "main";  # name of the last category interrogated
209    my $LastLevel = 0;          # level of the last test call
210  my $SetupCount = 0;         # number of times TSetup called  my $SetupCount = 0;         # number of times TSetup called
211  my $AllTrace = 0;           # TRUE if we are tracing all categories.  my $AllTrace = 0;           # TRUE if we are tracing all categories.
212    my $SavedCGI;               # CGI object passed to ETracing
213    my $CommandLine;            # Command line passed to StandardSetup
214    my $Confessions = 0;        # confession count
215    umask 2;                    # Fix the damn umask so everything is group-writable.
216    
217    =head2 Tracing Methods
218    
219    =head3 Setups
220    
221        my $count = Tracer::Setups();
222    
223    Return the number of times L</TSetup> has been called.
224    
225    This method allows for the creation of conditional tracing setups where, for example, we
226    may want to set up tracing if nobody else has done it before us.
227    
228    =cut
229    
230  =head2 Public Methods  sub Setups {
231        return $SetupCount;
232    }
233    
234  =head3 TSetup  =head3 TSetup
235    
236  C<< TSetup($categoryList, $target); >>      TSetup($categoryList, $target);
237    
238  This method is used to specify the trace options. The options are stored as package data  This method is used to specify the trace options. The options are stored as package data
239  and interrogated by the L</Trace> and L</T> methods.  and interrogated by the L</Trace> and L</T> methods.
# Line 189  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() . " 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 211  Line 308 
308      $SetupCount++;      $SetupCount++;
309  }  }
310    
311  =head3 StandardSetup  =head3 SetLevel
312    
313  C<< my ($options, @parameters) = StandardSetup(\@categories, \%options, $parmHelp, @ARGV); >>      Tracer::SetLevel($newLevel);
314    
315  This method performs standard command-line parsing and tracing setup. The return  Modify the trace level. A higher trace level will cause more messages to appear.
 values are a hash of the command-line options and a list of the positional  
 parameters. Tracing is automatically set up and the command-line options are  
 validated.  
316    
317  This is a complex method that does a lot of grunt work. The parameters can  =over 4
 be more easily understood, however, once they are examined individually.  
318    
319  The I<categories> parameter is the most obtuse. It is a reference to a list of  =item newLevel
 special-purpose tracing categories. Most tracing categories are PERL package  
 names. So, for example, if you wanted to turn on tracing inside the B<Sprout>,  
 B<ERDB>, and B<SproutLoad> packages, you would specify the categories  
320    
321      ["Sprout", "SproutLoad", "ERDB"]  Proposed new trace level.
322    
323  This would cause trace messages in the specified three packages to appear in  =back
 the output. There are threer special tracing categories that are automatically  
 handled by this method. In other words, if you used L</TSetup> you would need  
 to include these categories manually, but if you use this method they are turned  
 on automatically.  
324    
325  =over 4  =cut
326    
327  =item FIG  sub SetLevel {
328        $TraceLevel = $_[0];
329    }
330    
331  Turns on trace messages inside the B<FIG> package.  =head3 ParseDate
332    
333  =item SQL      my $time = Tracer::ParseDate($dateString);
334    
335  Traces SQL commands and activity.  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  =item Tracer  If a time of day is present, it must be in military time with two digits for
342    everything but the hour.
343    
344  Traces error messages and call stacks.  The year must be exactly four digits.
345    
346  =back  Additional stuff can be in the string. We presume it's time zones or weekdays or something
347    equally innocuous. This means, however, that a sufficiently long sentence with date-like
348    parts in it may be interpreted as a date. Hopefully this will not be a problem.
349    
350  C<SQL> is only turned on if the C<-sql> option is specified in the command line.  It should be guaranteed that this method will parse the output of the L</Now> function.
 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.  
351    
352      TransactFeatures -trace=3 -sql register ../xacts IDs.tbl  The parameters are as follows.
353    
354  Standard tracing is output to the standard output and echoed to the file  =over 4
 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  
355    
356  The default trace level is 2. To get all messages, specify a trace level of 4.  =item dateString
 For a genome-by-genome update, use 3.  
357    
358      TransactFeatures -trace=3 -sql -user=Bruce register ../xacts IDs.tbl  The date string to convert.
359    
360  would send the trace output to C<traceBruce.log> in the temporary directory.  =item RETURN
361    
362  The I<options> parameter is a reference to a hash containing the command-line  Returns a PERL time, that is, a number of seconds since the epoch, or C<undef> if
363  options, their default values, and an explanation of what they mean. Command-line  the date string is invalid. A valid date string must contain a month and day.
 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.  
364    
365  You can specify a different default trace level by setting C<$options->{trace}>  =back
 prior to calling this method.  
366    
367  An example at this point would help. Consider, for example, the command-line utility  =cut
 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.  
368    
369      my ($options, @parameters) = Tracer::StandardSetup(["DocUtils"],  # Universal month conversion table.
370                          { safe => [0, "use database transactions"],  use constant MONTHS => {    Jan =>  0, January   =>  0, '01' =>  0,  '1' =>  0,
371                            noAlias => [0, "do not expect aliases in CHANGE transactions"],                              Feb =>  1, February  =>  1, '02' =>  1,  '2' =>  1,
372                            start => [' ', "start with this genome"],                              Mar =>  2, March     =>  2, '03' =>  2,  '3' =>  2,
373                            tblFiles => [0, "output TBL files containing the corrected IDs"] },                              Apr =>  3, April     =>  3, '04' =>  3,  '4' =>  3,
374                          "command transactionDirectory IDfile",                              May =>  4, May       =>  4, '05' =>  4,  '5' =>  4,
375                        @ARGV);                              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    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  The call to C<ParseCommand> specifies the default values for the options and  =head3 LogErrors
 stores the actual options in a hash that is returned as C<$options>. The  
 positional parameters are returned in C<@parameters>.  
419    
420  The following is a sample command line for C<TransactFeatures>.      Tracer::LogErrors($fileName);
421    
422      TransactFeatures -trace=2 -noAlias register ../xacts IDs.tbl  Route the standard error output to a log file.
423    
424  In this case, C<register>, C<../xacts>, and C<IDs.tbl> are the positional  =over 4
 parameters, and would find themselves in I<@parameters> after executing the  
 above code fragment. The tracing would be set to level 2, and the categories  
 would be C<FIG>, C<Tracer>, and <DocUtils>. C<FIG> and C<Tracer> are standard,  
 and C<DocUtils> was included because it came in within the first parameter  
 to this method. The I<$options> hash would be  
425    
426      { trace => 2, sql => 0, safe => 0,  =item fileName
       noAlias => 1, start => ' ', tblFiles => 0 }  
427    
428  Use of C<StandardSetup> in this way provides a simple way of performing  Name of the file to receive the error output.
 standard tracing setup and command-line parsing. Note that the caller is  
 not even aware of the command-line switches C<-trace> and C<-sql>, which  
 are used by this method to control the tracing. If additional tracing features  
 need to be added in the future, they can be processed by this method without  
 upsetting the command-line utilities.  
429    
430  If the C<background> option is specified on the command line, then the  =back
 standard and error outputs will be directed to files in the temporary  
 directory, using the same suffix as the trace file. So, if the command  
 line specified  
431    
432      -user=Bruce -background  =cut
433    
434  then the trace output would go to C<traceBruce.log>, the standard output to  sub LogErrors {
435  C<outBruce.log>, and the error output to C<errBruce.log>. This is designed to      # Get the file name.
436  simplify starting a command in the background.      my ($fileName) = @_;
437        # Open the file as the standard error output.
438        open STDERR, '>', $fileName;
439    }
440    
441  Finally, if the special option C<-h> is specified, the option names will  =head3 Trace
 be traced at level 0 and the program will exit without processing.  
 This provides a limited help capability. For example, if the user enters  
442    
443      TransactFeatures -h      Trace($message);
444    
445  he would see the following output.  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      TransactFeatures [options] command transactionDirectory IDfile  =over 4
         -trace    tracing level (default 2)  
         -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  
449    
450  The caller has the option of modifying the tracing scheme by placing a value  =item message
 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,  
451    
452      { trace => [0, "tracing level (default 0)"],  Message to write.
        ...  
453    
454  would set the default trace level to 0 instead of 2, while  =back
455    
456      { trace => ["2-", "tracing level (default 2)"],  =cut
        ...  
457    
458  would leave the default at 2, but trace only to the log file, not to the  sub Trace {
459  standard output.      # 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  The parameters to this method are as follows.  =head3 MemTrace
517    
518        MemTrace($message);
519    
520    Output a trace message that includes memory size information.
521    
522  =over 4  =over 4
523    
524  =item categories  =item message
525    
526  Reference to a list of tracing category names. These should be names of  Message to display. The message will be followed by a sentence about the memory size.
 packages whose internal workings will need to be debugged to get the  
 command working.  
527    
528  =item options  =back
529    
530  Reference to a hash containing the legal options for the current command mapped  =cut
 to their default values and descriptions. The user can override the defaults  
 by specifying the options as command-line switches prefixed by a hyphen.  
 Tracing-related options may be added to this hash. If the C<-h> option is  
 specified on the command line, the option descriptions will be used to  
 explain the options. To turn off tracing to the standard output, add a  
 minus sign to the value for C<trace> (see above).  
531    
532  =item parmHelp  sub MemTrace {
533        # Get the parameters.
534        my ($message) = @_;
535        my $memory = GetMemorySize();
536        Trace("$message $memory in use.");
537    }
538    
 A string that vaguely describes the positional parameters. This is used  
 if the user specifies the C<-h> option.  
539    
540  =item argv  =head3 TraceDump
541    
542  List of command line parameters, including the option switches, which must      TraceDump($title, $object);
 precede the positional parameters and be prefixed by a hyphen.  
543    
544  =item RETURN  Dump an object to the trace log. This method simply calls the C<Dumper>
545    function, but routes the output to the trace log instead of returning it
546    as a string. The output is arranged so that it comes out monospaced when
547    it appears in an HTML trace dump.
548    
549  Returns a list. The first element of the list is the reference to a hash that  =over 4
550  maps the command-line option switches to their values. These will either be the  
551  default values or overrides specified on the command line. The remaining  =item title
552  elements of the list are the position parameters, in order.  
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  =back
560    
561  =cut  =cut
562    
563  sub StandardSetup {  sub TraceDump {
564      # Get the parameters.      # Get the parameters.
565      my ($categories, $options, $parmHelp, @argv) = @_;      my ($title, $object) = @_;
566      # Add the tracing options.      # Trace the object.
567      if (! exists $options->{trace}) {      Trace("Object dump for $title:\n" . Dumper($object));
         $options->{trace} = [2, "tracing level"];  
568      }      }
569      $options->{sql} = [0, "turn on SQL tracing"];  
570      $options->{h} = [0, "display command-line options"];  =head3 T
571      $options->{user} = [$$, "trace log file name suffix"];  
572      $options->{background} = [0, "spool standard and error output"];      my $switch = T($category, $traceLevel);
573      # Create a parsing hash from the options hash. The parsing hash  
574      # contains the default values rather than the default value      or
575      # and the description. While we're at it, we'll memorize the  
576      # length of the longest option name.      my $switch = T($traceLevel);
577      my $longestName = 0;  
578      my %parseOptions = ();  Return TRUE if the trace level is at or above a specified value and the specified category
579      for my $key (keys %{$options}) {  is active, else FALSE. If no category is specified, the caller's package name is used.
580    
581    =over 4
582    
583    =item category
584    
585    Category to which the message belongs. If not specified, the caller's package name is
586    used.
587    
588    =item traceLevel
589    
590    Relevant tracing level.
591    
592    =item RETURN
593    
594    TRUE if a message at the specified trace level would appear in the trace, else FALSE.
595    
596    =back
597    
598    =cut
599    
600    sub T {
601        # Declare the return variable.
602        my $retVal = 0;
603        # Only proceed if tracing is turned on.
604        if ($Destination ne "NONE") {
605            # Get the parameters.
606            my ($category, $traceLevel) = @_;
607            if (!defined $traceLevel) {
608                # Here we have no category, so we need to get the calling package.
609                # The calling package is normally the first parameter. If it is
610                # omitted, the first parameter will be the tracelevel. So, the
611                # first thing we do is shift the so-called category into the
612                # $traceLevel variable where it belongs.
613                $traceLevel = $category;
614                my ($package, $fileName, $line) = caller;
615                # If there is no calling package, we default to "main".
616                if (!$package) {
617                    $category = "main";
618                } else {
619                    my @cats = split /::/, $package;
620                    $category = $cats[$#cats];
621                }
622            }
623            # Save the category name and level.
624            $LastCategory = $category;
625            $LastLevel = $traceLevel;
626            # Convert it to lower case before we hash it.
627            $category = lc $category;
628            # Validate the trace level.
629            if (ref $traceLevel) {
630                Confess("Bad trace level.");
631            } elsif (ref $TraceLevel) {
632                Confess("Bad trace config.");
633            }
634            # Make the check. Note that level 0 shows even if the category is turned off.
635            $retVal = ($traceLevel <= $TraceLevel && ($traceLevel == 0 || $AllTrace || exists $Categories{$category}));
636        }
637        # Return the computed result.
638        return $retVal;
639    }
640    
641    =head3 QTrace
642    
643        my $data = QTrace($format);
644    
645    Return the queued trace data in the specified format.
646    
647    =over 4
648    
649    =item format
650    
651    C<html> to format the data as an HTML list, C<text> to format it as straight text.
652    
653    =back
654    
655    =cut
656    
657    sub QTrace {
658        # Get the parameter.
659        my ($format) = @_;
660        # Create the return variable.
661        my $retVal = "";
662        # Only proceed if there is an actual queue.
663        if (@Queue) {
664            # Process according to the format.
665            if ($format =~ m/^HTML$/i) {
666                # Convert the queue into an HTML list.
667                $retVal = "<ul>\n";
668                for my $line (@Queue) {
669                    my $escapedLine = CGI::escapeHTML($line);
670                    $retVal .= "<li>$escapedLine</li>\n";
671                }
672                $retVal .= "</ul>\n";
673            } elsif ($format =~ m/^TEXT$/i) {
674                # Convert the queue into a list of text lines.
675                $retVal = join("\n", @Queue) . "\n";
676            }
677            # Clear the queue.
678            @Queue = ();
679        }
680        # Return the formatted list.
681        return $retVal;
682    }
683    
684    =head3 Confess
685    
686        Confess($message);
687    
688    Trace the call stack and abort the program with the specified message. When used with
689    the OR operator and the L</Assert> method, B<Confess> can function as a debugging assert.
690    So, for example
691    
692        Assert($recNum >= 0) || Confess("Invalid record number $recNum.");
693    
694    Will abort the program with a stack trace if the value of C<$recNum> is negative.
695    
696    =over 4
697    
698    =item message
699    
700    Message to include in the trace.
701    
702    =back
703    
704    =cut
705    
706    sub Confess {
707        # Get the parameters.
708        my ($message) = @_;
709        # Set up the category and level.
710        $LastCategory = "(confess)";
711        $LastLevel = 0;
712        # Trace the call stack.
713        Cluck($message);
714        # Increment the confession count.
715        $Confessions++;
716        # Abort the program.
717        croak(">>> $message");
718    }
719    
720    =head3 Confessions
721    
722        my $count = Tracer::Confessions();
723    
724    Return the number of calls to L</Confess> by the current task.
725    
726    =cut
727    
728    sub Confessions {
729        return $Confessions;
730    }
731    
732    
733    =head3 SaveCGI
734    
735        Tracer::SaveCGI($cgi);
736    
737    This method saves the CGI object but does not activate emergency tracing.
738    It is used to allow L</Warn> to work in situations where emergency
739    tracing is contra-indicated (e.g. the wiki).
740    
741    =over 4
742    
743    =item cgi
744    
745    Active CGI query object.
746    
747    =back
748    
749    =cut
750    
751    sub SaveCGI {
752        $SavedCGI = $_[0];
753    }
754    
755    =head3 Warn
756    
757        Warn($message, @options);
758    
759    This method traces an important message. If an RSS feed is configured
760    (via I<FIG_Config::error_feed>) and the tracing destination is C<WARN>,
761    then the message will be echoed to the feed. In general, a tracing
762    destination of C<WARN> indicates that the caller is running as a web
763    service in a production environment; however, this is not a requirement.
764    
765    To force warnings into the RSS feed even when the tracing destination
766    is not C<WARN>, simply specify the C<Feed> tracing module. This can be
767    configured automatically when L</StandardSetup> is used.
768    
769    The L</Cluck> method calls this one for its final message. Since
770    L</Confess> calls L</Cluck>, this means that any error which is caught
771    and confessed will put something in the feed. This insures that someone
772    will be alerted relatively quickly when a failure occurs.
773    
774    =over 4
775    
776    =item message
777    
778    Message to be traced.
779    
780    =item options
781    
782    A list containing zero or more options.
783    
784    =back
785    
786    The permissible options are as follows.
787    
788    =over 4
789    
790    =item noStack
791    
792    If specified, then the stack trace is not included in the output.
793    
794    =back
795    
796    =cut
797    
798    sub Warn {
799        # Get the parameters.
800        my $message = shift @_;
801        my %options = map { $_ => 1 } @_;
802        # Save $@;
803        my $savedError = $@;
804        # Trace the message.
805        Trace($message);
806        # This will contain the lock handle. If it's defined, it means we need to unlock.
807        my $lock;
808        # Check for feed forcing.
809        my $forceFeed = exists $Categories{feed};
810        # An error here would be disastrous. Note that if debug mode is specified,
811        # we do this stuff even in a test environment.
812        eval {
813            # Do we need to put this in the RSS feed?
814            if ($FIG_Config::error_feed && ($Destination eq 'WARN' || $forceFeed)) {
815                # Probably. We need to check first, however, to see if it's from an
816                # ignored IP. For non-CGI situations, we default the IP to the self-referent.
817                my $key = "127.0.0.1";
818                if (defined $SavedCGI) {
819                    # Get the IP address.
820                    $key = $ENV{HTTP_X_FORWARDED_FOR} || $ENV{REMOTE_ADDR};
821                }
822                # Is the IP address in the ignore list?
823                my $found = scalar(grep { $_ eq $key } @FIG_Config::error_ignore_ips);
824                if (! $found) {
825                    # No. We're good. We now need to compute the date, the link, and the title.
826                    # First, the date, in a very specific format.
827                    my $date = strftime("%a, %02e %b %H:%M:%S %Y ", localtime) .
828                        (tz_local_offset() / 30);
829                    # Environment data goes in here. We start with the date.
830                    my $environment = "$date.  ";
831                    # If we need to recap the message (because it's too long to be a title), we'll
832                    # put it in here.
833                    my $recap;
834                    # Copy the message and remove excess space.
835                    my $title = $message;
836                    $title =~ s/\s+/ /gs;
837                    # If it's too long, we have to split it up.
838                    if (length $title > 60) {
839                        # Put the full message in the environment string.
840                        $recap = $title;
841                        # Excerpt it as the title.
842                        $title = substr($title, 0, 50) . "...";
843                    }
844                    # If we have a CGI object, then this is a web error. Otherwise, it's
845                    # command-line.
846                    if (defined $SavedCGI) {
847                        # We're in a web service. The environment is the user's IP, and the link
848                        # is the URL that got us here.
849                        $environment .= "Event Reported at IP address $key process $$.";
850                        my $url = $SavedCGI->self_url();
851                        # We need the user agent string and (if available) the referrer.
852                        # The referrer will be the link.
853                        $environment .= " User Agent $ENV{HTTP_USER_AGENT}";
854                        if ($ENV{HTTP_REFERER}) {
855                            my $link = $ENV{HTTP_REFERER};
856                            $environment .= " referred from <a href=\"$link\">$link</a>.";
857                        } else {
858                            $environment .= " referrer unknown.";
859                        }
860                        # Close off the sentence with the original link.
861                        $environment .= " URL of event is <a href=\"$url\">$url</a>.";
862                    } else {
863                        # No CGI object, so we're a command-line tool. Use the tracing
864                        # key and the PID as the user identifier, and add the command.
865                        my $key = EmergencyKey();
866                        $environment .= "Event Reported by $key process $$.";
867                        if ($CommandLine) {
868                            # We're in a StandardSetup script, so we have the real command line.
869                            $environment .= "\n<pre>" . CGI::escapeHTML($CommandLine) . "</pre>\n";
870                        } elsif ($ENV{_}) {
871                            # We're in a BASH script, so the command has been stored in the _ variable.
872                            $environment .= "  Command = " . CGI::escapeHTML($ENV{_}) . "\n";
873                        }
874                    }
875                    # Build a GUID. We use the current time, the title, and the process ID,
876                    # then digest the result.
877                    my $guid = Digest::MD5::md5_base64(gettimeofday(), $title, $$);
878                    # Finally, the description. This is a stack trace plus various environmental stuff.
879                    # The trace is optional.
880                    my $stackTrace;
881                    if ($options{noStack}) {
882                        $stackTrace = "";
883                    } else {
884                        my @trace = LongMess();
885                        # Only proceed if we got something back.
886                        if (scalar(@trace) > 0) {
887                            $trace[0] =~ s/Tracer::Warn.+?called/Event occurred/;
888                            $stackTrace = "Stack trace:<pre>" . join("\n", @trace, "</pre>");
889                        }
890                    }
891                    # We got the stack trace. Now it's time to put it all together.
892                    # We have a goofy thing here in that we need to HTML-escape some sections of the description
893                    # twice. They will be escaped once here, and then once when written by XML::Simple. They are
894                    # unescaped once when processed by the RSS reader, and stuff in the description is treated as
895                    # HTML. So, anything escaped here is treated as a literal when viewed in the RSS reader, but
896                    # our <br>s and <pre>s are used to format the description.
897                    $recap = (defined $recap ? "<em>" . CGI::escapeHTML($recap) . "</em><br /><br />" : "");
898                    my $description = "$recap$environment  $stackTrace";
899                    # Okay, we have all the pieces. Create a hash of the new event.
900                    my $newItem = { title => $title,
901                                    description => $description,
902                                    category => $LastCategory,
903                                    pubDate => $date,
904                                    guid => $guid,
905                                  };
906                    # We need XML capability for this.
907                    require XML::Simple;
908                    # The RSS document goes in here.
909                    my $rss;
910                    # Get the name of the RSS file. It's in the FIG temporary directory.
911                    my $fileName = "$FIG_Config::temp/$FIG_Config::error_feed";
912                    # Open the config file and lock it.
913                    $lock = Open(undef, "<$FIG_Config::fig_disk/config/FIG_Config.pm");
914                    flock $lock, LOCK_EX;
915                    # Does it exist?
916                    if (-s $fileName) {
917                        # Slurp it in.
918                        $rss = XML::Simple::XMLin($fileName, ForceArray => ['item']);
919                    } else {
920                        my $size = -s $fileName;
921                        # Create an empty channel.
922                        $rss = {
923                            channel => {
924                                title => 'NMPDR Warning Feed',
925                                link => "$FIG_Config::temp_url/$FIG_Config::error_feed",
926                                description => "Important messages regarding the status of the NMPDR.",
927                                generator => "NMPDR Trace Facility",
928                                docs => "http://blogs.law.harvard.edu/tech/rss",
929                                item => []
930                            },
931                        };
932                    }
933                    # Get the channel object.
934                    my $channel = $rss->{channel};
935                    # Update the last-build date.
936                    $channel->{lastBuildDate} = $date;
937                    # Get the item array.
938                    my $items = $channel->{item};
939                    # Insure it has only 100 entries.
940                    while (scalar @{$items} > 100) {
941                        pop @{$items};
942                    }
943                    # Add our new item at the front.
944                    unshift @{$items}, $newItem;
945                    # Create the XML. Note we do not include the root or the declaration. XML Simple can't handle
946                    # the requirements for those.
947                    my $xml = XML::Simple::XMLout($channel, NoAttr => 1, RootName => 'channel', XmlDecl => '');
948                    # Here we put in the root and declaration. The problem is that the root has to have the version attribute
949                    # in it. So, we suppress the root and do it by hand, and that requires suppressing the declaration, too.
950                    $xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<rss version=\"2.0\">$xml\n</rss>";
951                    # We don't use Open here because we can't afford an error.
952                    if (open XMLOUT, ">$fileName") {
953                        print XMLOUT $xml;
954                        close XMLOUT;
955                    }
956                }
957            }
958        };
959        if ($@) {
960            # If the feed failed, we need to know why. The error will be traced, but this method will not be involved
961            # (which is a good thing).
962            my $error = $@;
963            Trace("Feed Error: $error") if T(Feed => 0);
964        }
965        # Be sure to unlock.
966        if ($lock) {
967            flock $lock, LOCK_UN;
968            undef $lock;
969        }
970        # Restore the error message.
971        $@ = $savedError;
972    }
973    
974    
975    
976    
977    =head3 Assert
978    
979        Assert($condition1, $condition2, ... $conditionN);
980    
981    Return TRUE if all the conditions are true. This method can be used in conjunction with
982    the OR operator and the L</Confess> method as a debugging assert.
983    So, for example
984    
985        Assert($recNum >= 0) || Confess("Invalid record number $recNum.");
986    
987    Will abort the program with a stack trace if the value of C<$recNum> is negative.
988    
989    =cut
990    sub Assert {
991        my $retVal = 1;
992        LOOP: for my $condition (@_) {
993            if (! $condition) {
994                $retVal = 0;
995                last LOOP;
996            }
997        }
998        return $retVal;
999    }
1000    
1001    =head3 Cluck
1002    
1003        Cluck($message);
1004    
1005    Trace the call stack. Note that for best results, you should qualify the call with a
1006    trace condition. For example,
1007    
1008        Cluck("Starting record parse.") if T(3);
1009    
1010    will only trace the stack if the trace level for the package is 3 or more.
1011    
1012    =over 4
1013    
1014    =item message
1015    
1016    Message to include in the trace.
1017    
1018    =back
1019    
1020    =cut
1021    
1022    sub Cluck {
1023        # Get the parameters.
1024        my ($message) = @_;
1025        # Trace what's happening.
1026        Trace("Stack trace for event: $message");
1027        # Get the stack trace.
1028        my @trace = LongMess();
1029        # Convert the trace to a series of messages.
1030        for my $line (@trace) {
1031            # Replace the tab at the beginning with spaces.
1032            $line =~ s/^\t/    /;
1033            # Trace the line.
1034            Trace($line);
1035        }
1036        # Issue a warning. This displays the event message and inserts it into the RSS error feed.
1037        Warn($message);
1038    }
1039    
1040    =head3 LongMess
1041    
1042        my @lines = Tracer::LongMess();
1043    
1044    Return a stack trace with all tracing methods removed. The return will be in the form of a list
1045    of message strings.
1046    
1047    =cut
1048    
1049    sub LongMess {
1050        # Declare the return variable.
1051        my @retVal = ();
1052        my $confession = longmess("");
1053        for my $line (split /\s*\n/, $confession) {
1054            unless ($line =~ /Tracer\.pm/) {
1055                # Here we have a line worth keeping. Push it onto the result list.
1056                push @retVal, $line;
1057            }
1058        }
1059        # Return the result.
1060        return @retVal;
1061    }
1062    
1063    =head3 ETracing
1064    
1065        ETracing($parameter, $noParms);
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 noParms
1087    
1088    If TRUE, then CGI parameter tracing will be suppressed. The default is FALSE.
1089    
1090    =back
1091    
1092    =cut
1093    
1094    sub ETracing {
1095        # Get the parameter.
1096        my ($parameter, $noParms) = @_;
1097        # Check for CGI mode.
1098        if (defined $parameter && ref $parameter eq 'CGI') {
1099            $SavedCGI = $parameter;
1100        } else {
1101            $SavedCGI = undef;
1102        }
1103        # Default to no tracing except errors.
1104        my ($tracing, $dest) = ("0", "WARN");
1105        # Check for emergency tracing.
1106        my $tkey = EmergencyKey($parameter);
1107        my $emergencyFile = EmergencyFileName($tkey);
1108        if (-e $emergencyFile) {
1109            # We have the file. Read in the data.
1110            my @tracing = GetFile($emergencyFile);
1111            # Pull off the time limit.
1112            my $expire = shift @tracing;
1113            # Convert it to seconds.
1114            $expire *= 3600;
1115            # Check the file data.
1116            my $stat = stat($emergencyFile);
1117            my ($now) = gettimeofday;
1118            if ($now - $stat->mtime > $expire) {
1119                # Delete the expired file.
1120                unlink $emergencyFile;
1121            } else {
1122                # Emergency tracing is on. Pull off the destination and
1123                # the trace level;
1124                $dest = shift @tracing;
1125                my $level = shift @tracing;
1126                # Convert the destination to a real tracing destination.
1127                # temp directory.
1128                $dest = EmergencyTracingDest($tkey, $dest);
1129                # Insure Tracer is specified.
1130                my %moduleHash = map { $_ => 1 } @tracing;
1131                $moduleHash{Tracer} = 1;
1132                # Set the trace parameter.
1133                $tracing = join(" ", $level, sort keys %moduleHash);
1134            }
1135        } elsif (defined $SavedCGI) {
1136            # There's no emergency tracing, but we have a CGI object, so check
1137            # for tracing from the form parameters.
1138            if ($SavedCGI->param('Trace')) {
1139                # Here the user has requested tracing via a form.
1140                $dest = ($SavedCGI->param('TF') ? ">$FIG_Config::temp/Trace$$.log" : "QUEUE");
1141                $tracing = $SavedCGI->param('Trace') . " Tracer";
1142            }
1143        }
1144        # Setup the tracing we've determined from all the stuff above.
1145        TSetup($tracing, $dest);
1146        # Check to see if we're a web script.
1147        if (defined $SavedCGI && ! $noParms) {
1148            # Yes we are. Trace the form and environment data.
1149            TraceParms($SavedCGI);
1150            # Check for RAW mode. In raw mode, we print a fake header so that we see everything
1151            # emitted by the script in its raw form.
1152            if (T(Raw => 3)) {
1153                print CGI::header(-type => 'text/plain', -tracing => 'Raw');
1154            }
1155        }
1156    }
1157    
1158    =head3 EmergencyFileName
1159    
1160        my $fileName = Tracer::EmergencyFileName($tkey);
1161    
1162    Return the emergency tracing file name. This is the file that specifies
1163    the tracing information.
1164    
1165    =over 4
1166    
1167    =item tkey
1168    
1169    Tracing key for the current program.
1170    
1171    =item RETURN
1172    
1173    Returns the name of the file to contain the emergency tracing information.
1174    
1175    =back
1176    
1177    =cut
1178    
1179    sub EmergencyFileName {
1180        # Get the parameters.
1181        my ($tkey) = @_;
1182        # Compute the emergency tracing file name.
1183        return "$FIG_Config::temp/Emergency$tkey.txt";
1184    }
1185    
1186    =head3 EmergencyFileTarget
1187    
1188        my $fileName = Tracer::EmergencyFileTarget($tkey);
1189    
1190    Return the emergency tracing target file name. This is the file that receives
1191    the tracing output for file-based tracing.
1192    
1193    =over 4
1194    
1195    =item tkey
1196    
1197    Tracing key for the current program.
1198    
1199    =item RETURN
1200    
1201    Returns the name of the file to contain the trace output.
1202    
1203    =back
1204    
1205    =cut
1206    
1207    sub EmergencyFileTarget {
1208        # Get the parameters.
1209        my ($tkey) = @_;
1210        # Compute the emergency tracing file name.
1211        return "$FIG_Config::temp/trace$tkey.log";
1212    }
1213    
1214    =head3 EmergencyTracingDest
1215    
1216        my $dest = Tracer::EmergencyTracingDest($tkey, $myDest);
1217    
1218    This method converts an emergency tracing destination to a real
1219    tracing destination. The main difference is that if the
1220    destination is C<FILE> or C<APPEND>, we convert it to file
1221    output. If the destination is C<DUAL>, we convert it to file
1222    and standard output.
1223    
1224    =over 4
1225    
1226    =item tkey
1227    
1228    Tracing key for this environment.
1229    
1230    =item myDest
1231    
1232    Destination from the emergency tracing file.
1233    
1234    =item RETURN
1235    
1236    Returns a destination that can be passed into L</TSetup>.
1237    
1238    =back
1239    
1240    =cut
1241    
1242    sub EmergencyTracingDest {
1243        # Get the parameters.
1244        my ($tkey, $myDest) = @_;
1245        # Declare the return variable.
1246        my $retVal = $myDest;
1247        # Process according to the destination value.
1248        if ($myDest eq 'FILE') {
1249            $retVal = ">" . EmergencyFileTarget($tkey);
1250        } elsif ($myDest eq 'APPEND') {
1251            $retVal = ">>" . EmergencyFileTarget($tkey);
1252        } elsif ($myDest eq 'DUAL') {
1253            $retVal = "+>" . EmergencyFileTarget($tkey);
1254        } elsif ($myDest eq 'WARN') {
1255            $retVal = "WARN";
1256        }
1257        # Return the result.
1258        return $retVal;
1259    }
1260    
1261    =head3 Emergency
1262    
1263        Emergency($key, $hours, $dest, $level, @modules);
1264    
1265    Turn on emergency tracing. This method is normally invoked over the web from
1266    a debugging console, but it can also be called by the C<trace.pl> script.
1267    The caller specifies the duration of the emergency in hours, the desired tracing
1268    destination, the trace level, and a list of the trace modules to activate.
1269    For the length of the duration, when a program in an environment with the
1270    specified tracing key active invokes a Sprout CGI script, tracing will be
1271    turned on automatically. See L</TSetup> for more about tracing setup and
1272    L</ETracing> for more about emergency tracing.
1273    
1274    =over 4
1275    
1276    =item tkey
1277    
1278    The tracing key. This is used to identify the control file and the trace file.
1279    
1280    =item hours
1281    
1282    Number of hours to keep emergency tracing alive.
1283    
1284    =item dest
1285    
1286    Tracing destination. If no path information is specified for a file
1287    destination, it is put in the FIG temporary directory.
1288    
1289    =item level
1290    
1291    Tracing level. A higher level means more trace messages.
1292    
1293    =item modules
1294    
1295    A list of the tracing modules to activate.
1296    
1297    =back
1298    
1299    =cut
1300    
1301    sub Emergency {
1302        # Get the parameters.
1303        my ($tkey, $hours, $dest, $level, @modules) = @_;
1304        # Create the emergency file.
1305        my $specFile = EmergencyFileName($tkey);
1306        my $outHandle = Open(undef, ">$specFile");
1307        print $outHandle join("\n", $hours, $dest, $level, @modules, "");
1308    }
1309    
1310    =head3 EmergencyKey
1311    
1312        my $tkey = EmergencyKey($parameter);
1313    
1314    Return the Key to be used for emergency tracing. This could be an IP address,
1315     a session ID, or a user name, depending on the environment.
1316    
1317    =over 4
1318    
1319    =item parameter
1320    
1321    Parameter defining the method for finding the tracing key. If it is a scalar,
1322    then it is presumed to be the tracing key itself. If it is a CGI object, then
1323    the tracing key is taken from the C<IP> cookie. Otherwise, the tracing key is
1324    taken from the C<TRACING> environment variable.
1325    
1326    =item RETURN
1327    
1328    Returns the key to be used for labels in emergency tracing.
1329    
1330    =back
1331    
1332    =cut
1333    
1334    sub EmergencyKey {
1335        # Get the parameters.
1336        my ($parameter) = @_;
1337        # Declare the return variable.
1338        my $retVal;
1339        # Determine the parameter type.
1340        if (! defined $parameter || defined($ENV{TRACING})) {
1341            # Here we're supposed to check the environment. If that fails, we
1342            # get the effective login ID.
1343            $retVal = $ENV{TRACING} || scalar getpwuid($<);
1344        } else {
1345            my $ptype = ref $parameter;
1346            if ($ptype eq 'CGI') {
1347                # Here we were invoked from a web page. Look for a cookie.
1348                $retVal = $parameter->cookie('IP');
1349            } elsif (! $ptype) {
1350                # Here the key was passed in.
1351                $retVal = $parameter;
1352            }
1353        }
1354        # If no luck finding a key, use the PID.
1355        if (! defined $retVal) {
1356            $retVal = $$;
1357        }
1358        # Return the result.
1359        return $retVal;
1360    }
1361    
1362    
1363    =head3 TraceParms
1364    
1365        Tracer::TraceParms($cgi);
1366    
1367    Trace the CGI parameters at trace level CGI => 3 and the environment variables
1368    at level CGI => 4. A self-referencing URL is traced at level CGI => 2.
1369    
1370    =over 4
1371    
1372    =item cgi
1373    
1374    CGI query object containing the parameters to trace.
1375    
1376    =back
1377    
1378    =cut
1379    
1380    sub TraceParms {
1381        # Get the parameters.
1382        my ($cgi) = @_;
1383        if (T(CGI => 2)) {
1384            # Here we trace the GET-style URL for the script, but only if it's
1385            # relatively small.
1386            my $url = $cgi->url(-relative => 1, -query => 1);
1387            my $len = length($url);
1388            if ($len < 500) {
1389                Trace("[URL] $url");
1390            } elsif ($len > 2048) {
1391                Trace("[URL] URL is too long to use with GET ($len characters).");
1392            } else {
1393                Trace("[URL] URL length is $len characters.");
1394            }
1395        }
1396        if (T(CGI => 3)) {
1397            # Here we want to trace the parameter data.
1398            my @names = $cgi->param;
1399            for my $parmName (sort @names) {
1400                # Note we skip the Trace parameters, which are for our use only.
1401                if ($parmName ne 'Trace' && $parmName ne 'TF') {
1402                    my @values = $cgi->param($parmName);
1403                    Trace("[CGI] $parmName = " . join(", ", @values));
1404                }
1405            }
1406            # Display the request method.
1407            my $method = $cgi->request_method();
1408            Trace("Method: $method");
1409        }
1410        if (T(CGI => 4)) {
1411            # Here we want the environment data too.
1412            for my $envName (sort keys %ENV) {
1413                Trace("[ENV] $envName = $ENV{$envName}");
1414            }
1415        }
1416    }
1417    
1418    =head3 TraceImages
1419    
1420        Tracer::TraceImages($htmlString);
1421    
1422    Trace information about all of an html document's images. The tracing
1423    will be for type "IMG" at level 3. The image's source string
1424    will be displayed. This is generally either the URL of the image or
1425    raw data for the image itself. If the source is too long, only the first 300
1426    characters will be shown at trace level 3. The entire source will be shown,
1427    however, at trace level 4. This method is not very smart, and might catch
1428    Javascript code, but it is still useful when debugging the arcane
1429    behavior of images in multiple browser environments.
1430    
1431    =over 4
1432    
1433    =item htmlString
1434    
1435    HTML text for an outgoing web page.
1436    
1437    =back
1438    
1439    =cut
1440    
1441    sub TraceImages {
1442        # Only proceed if we're at the proper trace level.
1443        if (T(IMG => 3)) {
1444            # For performance reasons we're manipulating $_[0] instead of retrieving the string
1445            # into a variable called "$htmlString". This is because we expect html strings to be
1446            # long, and don't want to copy them any more than we have to.
1447            Trace(length($_[0]) . " characters in web page.");
1448            # Loop through the HTML, culling image tags.
1449            while ($_[0] =~ /<img\s+[^>]+?src="([^"]+)"/sgi) {
1450                # Extract the source string and determine whether or not it's too long.
1451                my $srcString = $1;
1452                my $pos = pos($_[0]) - length($srcString);
1453                my $excess = length($srcString) - 300;
1454                # We'll put the display string in here.
1455                my $srcDisplay = $srcString;
1456                # If it's a data string, split it at the comma.
1457                $srcDisplay =~ s/^(data[^,]+,)/$1\n/;
1458                # If there's no excess or we're at trace level 4, we're done. At level 3 with
1459                # a long string, however, we only show the first 300 characters.
1460                if ($excess > 0 && ! T(IMG => 4)) {
1461                    $srcDisplay = substr($srcDisplay,0,300) . "\nplus $excess characters.";
1462                }
1463                # Output the trace message.
1464                Trace("Image tag at position $pos:\n$srcDisplay");
1465            }
1466        }
1467    }
1468    
1469    =head2 Command-Line Utility Methods
1470    
1471    =head3 SendSMS
1472    
1473        my $msgID = Tracer::SendSMS($phoneNumber, $msg);
1474    
1475    Send a text message to a phone number using Clickatell. The FIG_Config file must contain the
1476    user name, password, and API ID for the relevant account in the hash reference variable
1477    I<$FIG_Config::phone>, using the keys C<user>, C<password>, and C<api_id>. For
1478    example, if the user name is C<BruceTheHumanPet>, the password is C<silly>, and the API ID
1479    is C<2561022>, then the FIG_Config file must contain
1480    
1481        $phone =  { user => 'BruceTheHumanPet',
1482                    password => 'silly',
1483                    api_id => '2561022' };
1484    
1485    The original purpose of this method was to insure Bruce would be notified immediately when the
1486    Sprout Load terminates. Care should be taken if you do not wish Bruce to be notified immediately
1487    when you call this method.
1488    
1489    The message ID will be returned if successful, and C<undef> if an error occurs.
1490    
1491    =over 4
1492    
1493    =item phoneNumber
1494    
1495    Phone number to receive the message, in international format. A United States phone number
1496    would be prefixed by "1". A British phone number would be prefixed by "44".
1497    
1498    =item msg
1499    
1500    Message to send to the specified phone.
1501    
1502    =item RETURN
1503    
1504    Returns the message ID if successful, and C<undef> if the message could not be sent.
1505    
1506    =back
1507    
1508    =cut
1509    
1510    sub SendSMS {
1511        # Get the parameters.
1512        my ($phoneNumber, $msg) = @_;
1513        # Declare the return variable. If we do not change it, C<undef> will be returned.
1514        my $retVal;
1515        # Only proceed if we have phone support.
1516        if (! defined $FIG_Config::phone) {
1517            Trace("Phone support not present in FIG_Config.") if T(1);
1518        } else {
1519            # Get the phone data.
1520            my $parms = $FIG_Config::phone;
1521            # Get the Clickatell URL.
1522            my $url = "http://api.clickatell.com/http/";
1523            # Create the user agent.
1524            my $ua = LWP::UserAgent->new;
1525            # Request a Clickatell session.
1526            my $resp = $ua->post("$url/sendmsg", { user => $parms->{user},
1527                                         password => $parms->{password},
1528                                         api_id => $parms->{api_id},
1529                                         to => $phoneNumber,
1530                                         text => $msg});
1531            # Check for an error.
1532            if (! $resp->is_success) {
1533                Trace("Alert failed.") if T(1);
1534            } else {
1535                # Get the message ID.
1536                my $rstring = $resp->content;
1537                if ($rstring =~ /^ID:\s+(.*)$/) {
1538                    $retVal = $1;
1539                } else {
1540                    Trace("Phone attempt failed with $rstring") if T(1);
1541                }
1542            }
1543        }
1544        # Return the result.
1545        return $retVal;
1546    }
1547    
1548    =head3 StandardSetup
1549    
1550        my ($options, @parameters) = StandardSetup(\@categories, \%options, $parmHelp, @ARGV);
1551    
1552    This method performs standard command-line parsing and tracing setup. The return
1553    values are a hash of the command-line options and a list of the positional
1554    parameters. Tracing is automatically set up and the command-line options are
1555    validated.
1556    
1557    This is a complex method that does a lot of grunt work. The parameters can
1558    be more easily understood, however, once they are examined individually.
1559    
1560    The I<categories> parameter is the most obtuse. It is a reference to a list of
1561    special-purpose tracing categories. Most tracing categories are PERL package
1562    names. So, for example, if you wanted to turn on tracing inside the B<Sprout>,
1563    B<ERDB>, and B<SproutLoad> packages, you would specify the categories
1564    
1565        ["Sprout", "SproutLoad", "ERDB"]
1566    
1567    This would cause trace messages in the specified three packages to appear in
1568    the output. There are two special tracing categories that are automatically
1569    handled by this method. In other words, if you used L</TSetup> you would need
1570    to include these categories manually, but if you use this method they are turned
1571    on automatically.
1572    
1573    =over 4
1574    
1575    =item SQL
1576    
1577    Traces SQL commands and activity.
1578    
1579    =item Tracer
1580    
1581    Traces error messages and call stacks.
1582    
1583    =back
1584    
1585    C<SQL> is only turned on if the C<-sql> option is specified in the command line.
1586    The trace level is specified using the C<-trace> command-line option. For example,
1587    the following command line for C<TransactFeatures> turns on SQL tracing and runs
1588    all tracing at level 3.
1589    
1590        TransactFeatures -trace=3 -sql register ../xacts IDs.tbl
1591    
1592    Standard tracing is output to the standard output and echoed to the file
1593    C<trace>I<$$>C<.log> in the FIG temporary directory, where I<$$> is the
1594    process ID. You can also specify the C<user> parameter to put a user ID
1595    instead of a process ID in the trace file name. So, for example
1596    
1597    The default trace level is 2. To get all messages, specify a trace level of 4.
1598    For a genome-by-genome update, use 3.
1599    
1600        TransactFeatures -trace=3 -sql -user=Bruce register ../xacts IDs.tbl
1601    
1602    would send the trace output to C<traceBruce.log> in the temporary directory.
1603    
1604    The I<options> parameter is a reference to a hash containing the command-line
1605    options, their default values, and an explanation of what they mean. Command-line
1606    options may be in the form of switches or keywords. In the case of a switch, the
1607    option value is 1 if it is specified and 0 if it is not specified. In the case
1608    of a keyword, the value is separated from the option name by an equal sign. You
1609    can see this last in the command-line example above.
1610    
1611    You can specify a different default trace level by setting C<$options->{trace}>
1612    prior to calling this method.
1613    
1614    An example at this point would help. Consider, for example, the command-line utility
1615    C<TransactFeatures>. It accepts a list of positional parameters plus the options
1616    C<safe>, C<noAlias>, C<start>, and C<tblFiles>. To start up this command, we execute
1617    the following code.
1618    
1619        my ($options, @parameters) = Tracer::StandardSetup(["DocUtils"],
1620                            { safe => [0, "use database transactions"],
1621                              noAlias => [0, "do not expect aliases in CHANGE transactions"],
1622                              start => [' ', "start with this genome"],
1623                              tblFiles => [0, "output TBL files containing the corrected IDs"] },
1624                            "<command> <transactionDirectory> <IDfile>",
1625                          @ARGV);
1626    
1627    
1628    The call to C<ParseCommand> specifies the default values for the options and
1629    stores the actual options in a hash that is returned as C<$options>. The
1630    positional parameters are returned in C<@parameters>.
1631    
1632    The following is a sample command line for C<TransactFeatures>.
1633    
1634        TransactFeatures -trace=2 -noAlias register ../xacts IDs.tbl
1635    
1636    Single and double hyphens are equivalent. So, you could also code the
1637    above command as
1638    
1639        TransactFeatures --trace=2 --noAlias register ../xacts IDs.tbl
1640    
1641    In this case, C<register>, C<../xacts>, and C<IDs.tbl> are the positional
1642    parameters, and would find themselves in I<@parameters> after executing the
1643    above code fragment. The tracing would be set to level 2, and the categories
1644    would be C<Tracer>, and <DocUtils>. C<Tracer> is standard,
1645    and C<DocUtils> was included because it came in within the first parameter
1646    to this method. The I<$options> hash would be
1647    
1648        { trace => 2, sql => 0, safe => 0,
1649          noAlias => 1, start => ' ', tblFiles => 0 }
1650    
1651    Use of C<StandardSetup> in this way provides a simple way of performing
1652    standard tracing setup and command-line parsing. Note that the caller is
1653    not even aware of the command-line switches C<-trace> and C<-sql>, which
1654    are used by this method to control the tracing. If additional tracing features
1655    need to be added in the future, they can be processed by this method without
1656    upsetting the command-line utilities.
1657    
1658    If the C<background> option is specified on the command line, then the
1659    standard and error outputs will be directed to files in the temporary
1660    directory, using the same suffix as the trace file. So, if the command
1661    line specified
1662    
1663        -user=Bruce -background
1664    
1665    then the trace output would go to C<traceBruce.log>, the standard output to
1666    C<outBruce.log>, and the error output to C<errBruce.log>. This is designed to
1667    simplify starting a command in the background.
1668    
1669    The user name is also used as the tracing key for L</Emergency Tracing>.
1670    Specifying a value of C<E> for the trace level causes emergency tracing to
1671    be used instead of custom tracing. If the user name is not specified,
1672    the tracing key is taken from the C<Tracing> environment variable. If there
1673    is no value for that variable, the tracing key will be computed from the active
1674    login ID.
1675    
1676    Since the default situation in StandardSetup is to trace to the standard
1677    output, errors that occur in command-line scripts will not generate
1678    RSS events. To force the events, use the C<warn> option.
1679    
1680        TransactFeatures -background -warn register ../xacts IDs.tbl
1681    
1682    Finally, if the special option C<-help> is specified, the option
1683    names will be traced at level 0 and the program will exit without processing.
1684    This provides a limited help capability. For example, if the user enters
1685    
1686        TransactFeatures -help
1687    
1688    he would see the following output.
1689    
1690        TransactFeatures [options] <command> <transactionDirectory> <IDfile>
1691            -trace    tracing level (default E)
1692            -sql      trace SQL commands
1693            -safe     use database transactions
1694            -noAlias  do not expect aliases in CHANGE transactions
1695            -start    start with this genome
1696            -tblFiles output TBL files containing the corrected IDs
1697            -forked   do not erase the trace file before tracing
1698    
1699    The caller has the option of modifying the tracing scheme by placing a value
1700    for C<trace> in the incoming options hash. The default value can be overridden,
1701    or the tracing to the standard output can be turned off by suffixing a minus
1702    sign to the trace level. So, for example,
1703    
1704        { trace => [0, "tracing level (default 0)"],
1705           ...
1706    
1707    would set the default trace level to 0 instead of E, while
1708    
1709        { trace => ["2-", "tracing level (default 2)"],
1710           ...
1711    
1712    would set the default to 2, but trace only to the log file, not to the
1713    standard output.
1714    
1715    The parameters to this method are as follows.
1716    
1717    =over 4
1718    
1719    =item categories
1720    
1721    Reference to a list of tracing category names. These should be names of
1722    packages whose internal workings will need to be debugged to get the
1723    command working.
1724    
1725    =item options
1726    
1727    Reference to a hash containing the legal options for the current command mapped
1728    to their default values and descriptions. The user can override the defaults
1729    by specifying the options as command-line switches prefixed by a hyphen.
1730    Tracing-related options may be added to this hash. If the C<-h> option is
1731    specified on the command line, the option descriptions will be used to
1732    explain the options. To turn off tracing to the standard output, add a
1733    minus sign to the value for C<trace> (see above).
1734    
1735    =item parmHelp
1736    
1737    A string that vaguely describes the positional parameters. This is used
1738    if the user specifies the C<-h> option.
1739    
1740    =item argv
1741    
1742    List of command line parameters, including the option switches, which must
1743    precede the positional parameters and be prefixed by a hyphen.
1744    
1745    =item RETURN
1746    
1747    Returns a list. The first element of the list is the reference to a hash that
1748    maps the command-line option switches to their values. These will either be the
1749    default values or overrides specified on the command line. The remaining
1750    elements of the list are the position parameters, in order.
1751    
1752    =back
1753    
1754    =cut
1755    
1756    sub StandardSetup {
1757        # Get the parameters.
1758        my ($categories, $options, $parmHelp, @argv) = @_;
1759        # Get the default tracing key.
1760        my $tkey = EmergencyKey();
1761        # Save the command line.
1762        $CommandLine = join(" ", $0, map { $_ =~ /\s/ ? "\"$_\"" : $_ } @argv);
1763        # Add the tracing options.
1764        if (! exists $options->{trace}) {
1765            $options->{trace} = ['2', "tracing level (E for emergency tracing)"];
1766        }
1767        if (! exists $options->{forked}) {
1768            $options->{forked} = [0, "keep old trace file"];
1769        }
1770        $options->{sql} = [0, "turn on SQL tracing"];
1771        $options->{help} = [0, "display command-line options"];
1772        $options->{user} = [$tkey, "tracing key"];
1773        $options->{background} = [0, "spool standard and error output"];
1774        $options->{warn} = [0, "send errors to RSS feed"];
1775        $options->{moreTracing} = ["", "comma-delimited list of additional trace modules for debugging"];
1776        # Create a parsing hash from the options hash. The parsing hash
1777        # contains the default values rather than the default value
1778        # and the description. While we're at it, we'll memorize the
1779        # length of the longest option name.
1780        my $longestName = 0;
1781        my %parseOptions = ();
1782        for my $key (keys %{$options}) {
1783          if (length $key > $longestName) {          if (length $key > $longestName) {
1784              $longestName = length $key;              $longestName = length $key;
1785          }          }
1786          $parseOptions{$key} = $options->{$key}->[0];          $parseOptions{$key} = $options->{$key}->[0];
1787        }
1788        # Parse the command line.
1789        my ($retOptions, @retParameters) = ParseCommand(\%parseOptions, @argv);
1790        # Get the logfile suffix.
1791        my $suffix = $retOptions->{user};
1792        # We'll put the trace file name in here. We need it later if background
1793        # mode is on.
1794        my $traceFileName;
1795        # Now we want to set up tracing. First, we need to know if the user
1796        # wants emergency tracing.
1797        if ($retOptions->{trace} eq 'E') {
1798            ETracing($retOptions->{user});
1799        } else {
1800            # Here the tracing is controlled from the command line.
1801            my @cats = @{$categories};
1802            if ($retOptions->{sql}) {
1803                push @cats, "SQL";
1804            }
1805            if ($retOptions->{warn}) {
1806                push @cats, "Feed";
1807            }
1808            # Add the default categories.
1809            push @cats, "Tracer";
1810            # Check for more tracing groups.
1811            if ($retOptions->{moreTracing}) {
1812                push @cats, split /,/, $retOptions->{moreTracing};
1813            }
1814            # Next, we create the category string by joining the categories.
1815            my $cats = join(" ", @cats);
1816            # Check to determine whether or not the caller wants to turn off tracing
1817            # to the standard output.
1818            my $traceLevel = $retOptions->{trace};
1819            my $textOKFlag = 1;
1820            if ($traceLevel =~ /^(.)-/) {
1821                $traceLevel = $1;
1822                $textOKFlag = 0;
1823            }
1824            # Now we set up the trace mode.
1825            my $traceMode;
1826            # Verify that we can open a file in the FIG temporary directory.
1827            my $traceFileName = "$FIG_Config::temp/trace$suffix.log";
1828            my $traceFileSpec = ($retOptions->{forked} ? ">>$traceFileName" : ">$traceFileName");
1829            if (open TESTTRACE, "$traceFileSpec") {
1830                # Here we can trace to a file.
1831                $traceMode = ">>$traceFileName";
1832                if ($textOKFlag) {
1833                    # Echo to standard output if the text-OK flag is set.
1834                    $traceMode = "+$traceMode";
1835                }
1836                # Close the test file.
1837                close TESTTRACE;
1838            } else {
1839                # Here we can't trace to a file. Complain about this.
1840                warn "Could not open trace file $traceFileName: $!\n";
1841                # We trace to the standard output if it's
1842                # okay, and the error log otherwise.
1843                if ($textOKFlag) {
1844                    $traceMode = "TEXT";
1845                } else {
1846                    $traceMode = "WARN";
1847                }
1848            }
1849            # Now set up the tracing.
1850            TSetup("$traceLevel $cats", $traceMode);
1851        }
1852        # Check for background mode.
1853        if ($retOptions->{background}) {
1854            my $outFileName = "$FIG_Config::temp/out$suffix$$.log";
1855            my $errFileName = "$FIG_Config::temp/err$suffix$$.log";
1856            # Spool the output.
1857            open STDOUT, ">$outFileName";
1858            # If we have a trace file, trace the errors to the log. Otherwise,
1859            # spool the errors.
1860            if (defined $traceFileName) {
1861                open STDERR, "| Tracer $traceFileName";
1862            } else {
1863                open STDERR, ">$errFileName";
1864            }
1865            # Check for phone support. If we have phone support and a phone number,
1866            # we want to turn it on.
1867            if ($ENV{PHONE} && defined($FIG_Config::phone)) {
1868                $retOptions->{phone} = $ENV{PHONE};
1869            }
1870        }
1871        # Check for the "help" option. If it is specified, dump the command-line
1872        # options and exit the program.
1873        if ($retOptions->{help}) {
1874            $0 =~ m#[/\\](\w+)(\.pl)?$#i;
1875            print "$1 [options] $parmHelp\n";
1876            for my $key (sort keys %{$options}) {
1877                my $name = Pad($key, $longestName, 0, ' ');
1878                my $desc = $options->{$key}->[1];
1879                if ($options->{$key}->[0]) {
1880                    $desc .= " (default " . $options->{$key}->[0] . ")";
1881                }
1882                print "  $name $desc\n";
1883            }
1884            exit(0);
1885        }
1886        # Trace the options, if applicable.
1887        if (T(3)) {
1888            my @parms = grep { $retOptions->{$_} } keys %{$retOptions};
1889            Trace("Selected options: " . join(", ", sort @parms) . ".");
1890        }
1891        # Return the parsed parameters.
1892        return ($retOptions, @retParameters);
1893    }
1894    
1895    =head3 ReadOptions
1896    
1897        my %options = Tracer::ReadOptions($fileName);
1898    
1899    Read a set of options from a file. Each option is encoded in a line of text that has the
1900    format
1901    
1902    I<optionName>C<=>I<optionValue>C<; >I<comment>
1903    
1904    The option name must consist entirely of letters, digits, and the punctuation characters
1905    C<.> and C<_>, and is case sensitive. Blank lines and lines in which the first nonblank
1906    character is a semi-colon will be ignored. The return hash will map each option name to
1907    the corresponding option value.
1908    
1909    =over 4
1910    
1911    =item fileName
1912    
1913    Name of the file containing the option data.
1914    
1915    =item RETURN
1916    
1917    Returns a hash mapping the option names specified in the file to their corresponding option
1918    value.
1919    
1920    =back
1921    
1922    =cut
1923    
1924    sub ReadOptions {
1925        # Get the parameters.
1926        my ($fileName) = @_;
1927        # Open the file.
1928        (open CONFIGFILE, "<$fileName") || Confess("Could not open option file $fileName.");
1929        # Count the number of records read.
1930        my ($records, $comments) = 0;
1931        # Create the return hash.
1932        my %retVal = ();
1933        # Loop through the file, accumulating key-value pairs.
1934        while (my $line = <CONFIGFILE>) {
1935            # Denote we've read a line.
1936            $records++;
1937            # Determine the line type.
1938            if ($line =~ /^\s*[\n\r]/) {
1939                # A blank line is a comment.
1940                $comments++;
1941            } elsif ($line =~ /^\s*([A-Za-z0-9_\.]+)=([^;]*);/) {
1942                # Here we have an option assignment.
1943                retVal{$1} = $2;
1944            } elsif ($line =~ /^\s*;/) {
1945                # Here we have a text comment.
1946                $comments++;
1947            } else {
1948                # Here we have an invalid line.
1949                Trace("Invalid option statement in record $records.") if T(0);
1950            }
1951        }
1952        # Return the hash created.
1953        return %retVal;
1954    }
1955    
1956    =head3 GetOptions
1957    
1958        Tracer::GetOptions(\%defaults, \%options);
1959    
1960    Merge a specified set of options into a table of defaults. This method takes two hash references
1961    as input and uses the data from the second to update the first. If the second does not exist,
1962    there will be no effect. An error will be thrown if one of the entries in the second hash does not
1963    exist in the first.
1964    
1965    Consider the following example.
1966    
1967        my $optionTable = GetOptions({ dbType => 'mySQL', trace => 0 }, $options);
1968    
1969    In this example, the variable B<$options> is expected to contain at most two options-- B<dbType> and
1970    B<trace>. The default database type is C<mySQL> and the default trace level is C<0>. If the value of
1971    B<$options> is C<< {dbType => 'Oracle'} >>, then the database type will be changed to C<Oracle> and
1972    the trace level will remain at 0. If B<$options> is undefined, then the database type and trace level
1973    will remain C<mySQL> and C<0>. If, on the other hand, B<$options> is defined as
1974    
1975        {databaseType => 'Oracle'}
1976    
1977    an error will occur because the B<databaseType> option does not exist.
1978    
1979    =over 4
1980    
1981    =item defaults
1982    
1983    Table of default option values.
1984    
1985    =item options
1986    
1987    Table of overrides, if any.
1988    
1989    =item RETURN
1990    
1991    Returns a reference to the default table passed in as the first parameter.
1992    
1993    =back
1994    
1995    =cut
1996    
1997    sub GetOptions {
1998        # Get the parameters.
1999        my ($defaults, $options) = @_;
2000        # Check for overrides.
2001        if ($options) {
2002            # Loop through the overrides.
2003            while (my ($option, $setting) = each %{$options}) {
2004                # Insure this override exists.
2005                if (!exists $defaults->{$option}) {
2006                    croak "Unrecognized option $option encountered.";
2007                } else {
2008                    # Apply the override.
2009                    $defaults->{$option} = $setting;
2010                }
2011      }      }
     # 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";  
2012      }      }
2013      # Now we want to set up tracing. First, we need to know if SQL is to      # Return the merged table.
2014      # be traced.      return $defaults;
     my @cats = @{$categories};  
     if ($retOptions->{sql}) {  
         push @cats, "SQL";  
2015      }      }
2016      # Add the default categories.  
2017      push @cats, "Tracer", "FIG";  =head3 MergeOptions
2018      # Next, we create the category string by joining the categories.  
2019      my $cats = join(" ", @cats);      Tracer::MergeOptions(\%table, \%defaults);
2020      # Check to determine whether or not the caller wants to turn off tracing  
2021      # to the standard output.  Merge default values into a hash table. This method looks at the key-value pairs in the
2022      my $traceLevel = $retOptions->{trace};  second (default) hash, and if a matching key is not found in the first hash, the default
2023      my $textOKFlag = 1;  pair is copied in. The process is similar to L</GetOptions>, but there is no error-
2024      if ($traceLevel =~ /^(.)-/) {  checking and no return value.
2025          $traceLevel = $1;  
2026          $textOKFlag = 0;  =over 4
2027    
2028    =item table
2029    
2030    Hash table to be updated with the default values.
2031    
2032    =item defaults
2033    
2034    Default values to be merged into the first hash table if they are not already present.
2035    
2036    =back
2037    
2038    =cut
2039    
2040    sub MergeOptions {
2041        # Get the parameters.
2042        my ($table, $defaults) = @_;
2043        # Loop through the defaults.
2044        while (my ($key, $value) = each %{$defaults}) {
2045            if (!exists $table->{$key}) {
2046                $table->{$key} = $value;
2047      }      }
     # Now we set up the trace mode.  
     my $traceMode;  
     # Verify that we can open a file in the FIG temporary directory.  
     my $traceFileName = "$FIG_Config::temp/trace$suffix.log";  
     if (open TESTTRACE, ">$traceFileName") {  
         # Here we can trace to a file.  
         $traceMode = ">$traceFileName";  
         if ($textOKFlag) {  
             # Echo to standard output if the text-OK flag is set.  
             $traceMode = "+$traceMode";  
2048          }          }
2049          # Close the test file.  }
2050          close TESTTRACE;  
2051    =head3 UnparseOptions
2052    
2053        my $optionString = Tracer::UnparseOptions(\%options);
2054    
2055    Convert an option hash into a command-line string. This will not
2056    necessarily be the same text that came in, but it will nonetheless
2057    produce the same ultimate result when parsed by L</StandardSetup>.
2058    
2059    =over 4
2060    
2061    =item options
2062    
2063    Reference to a hash of options to convert into an option string.
2064    
2065    =item RETURN
2066    
2067    Returns a string that will parse to the same set of options when
2068    parsed by L</StandardSetup>.
2069    
2070    =back
2071    
2072    =cut
2073    
2074    sub UnparseOptions {
2075        # Get the parameters.
2076        my ($options) = @_;
2077        # The option segments will be put in here.
2078        my @retVal = ();
2079        # Loop through the options.
2080        for my $key (keys %$options) {
2081            # Get the option value.
2082            my $value = $options->{$key};
2083            # Only use it if it's nonempty.
2084            if (defined $value && $value ne "") {
2085                my $segment = "--$key=$value";
2086                # Quote it if necessary.
2087                if ($segment =~ /[ |<>*]/) {
2088                    $segment = '"' . $segment . '"';
2089                }
2090                # Add it to the return list.
2091                push @retVal, $segment;
2092            }
2093        }
2094        # Return the result.
2095        return join(" ", @retVal);
2096    }
2097    
2098    =head3 ParseCommand
2099    
2100        my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList);
2101    
2102    Parse a command line consisting of a list of parameters. The initial parameters may be option
2103    specifiers of the form C<->I<option> or C<->I<option>C<=>I<value>. The options are stripped
2104    off and merged into a table of default options. The remainder of the command line is
2105    returned as a list of positional arguments. For example, consider the following invocation.
2106    
2107        my ($options, @arguments) = ParseCommand({ errors => 0, logFile => 'trace.log'}, @words);
2108    
2109    In this case, the list @words will be treated as a command line and there are two options available,
2110    B<errors> and B<logFile>. If @words has the following format
2111    
2112        -logFile=error.log apple orange rutabaga
2113    
2114    then at the end of the invocation, C<$options> will be
2115    
2116        { errors => 0, logFile => 'error.log' }
2117    
2118    and C<@arguments> will contain
2119    
2120        apple orange rutabaga
2121    
2122    The parser allows for some escape sequences. See L</UnEscape> for a description. There is no
2123    support for quote characters. Options can be specified with single or double hyphens.
2124    
2125    =over 4
2126    
2127    =item optionTable
2128    
2129    Table of default options.
2130    
2131    =item inputList
2132    
2133    List of words on the command line.
2134    
2135    =item RETURN
2136    
2137    Returns a reference to the option table and a list of the positional arguments.
2138    
2139    =back
2140    
2141    =cut
2142    
2143    sub ParseCommand {
2144        # Get the parameters.
2145        my ($optionTable, @inputList) = @_;
2146        # Process any options in the input list.
2147        my %overrides = ();
2148        while ((@inputList > 0) && ($inputList[0] =~ /^--?/)) {
2149            # Get the current option.
2150            my $arg = shift @inputList;
2151            # Pull out the option name.
2152            $arg =~ /^--?([^=]*)/g;
2153            my $name = $1;
2154            # Check for an option value.
2155            if ($arg =~ /\G=(.*)$/g) {
2156                # Here we have a value for the option.
2157                $overrides{$name} = UnEscape($1);
2158      } else {      } else {
2159          # Here we can't trace to a file. We trace to the standard output if it's              # Here there is no value, so we use 1.
2160          # okay, and the error log otherwise.              $overrides{$name} = 1;
2161          if ($textOKFlag) {          }
2162              $traceMode = "TEXT";      }
2163        # Merge the options into the defaults.
2164        GetOptions($optionTable, \%overrides);
2165        # Translate the remaining parameters.
2166        my @retVal = ();
2167        for my $inputParm (@inputList) {
2168            push @retVal, UnEscape($inputParm);
2169        }
2170        # Return the results.
2171        return ($optionTable, @retVal);
2172    }
2173    
2174    
2175    =head2 File Utility Methods
2176    
2177    =head3 GetFile
2178    
2179        my @fileContents = Tracer::GetFile($fileName);
2180    
2181        or
2182    
2183        my $fileContents = Tracer::GetFile($fileName);
2184    
2185    Return the entire contents of a file. In list context, line-ends are removed and
2186    each line is a list element. In scalar context, line-ends are replaced by C<\n>.
2187    
2188    =over 4
2189    
2190    =item fileName
2191    
2192    Name of the file to read.
2193    
2194    =item RETURN
2195    
2196    In a list context, returns the entire file as a list with the line terminators removed.
2197    In a scalar context, returns the entire file as a string. If an error occurs opening
2198    the file, an empty list will be returned.
2199    
2200    =back
2201    
2202    =cut
2203    
2204    sub GetFile {
2205        # Get the parameters.
2206        my ($fileName) = @_;
2207        # Declare the return variable.
2208        my @retVal = ();
2209        # Open the file for input.
2210        my $handle = Open(undef, "<$fileName");
2211        # Read the whole file into the return variable, stripping off any terminator
2212        # characters.
2213        my $lineCount = 0;
2214        while (my $line = <$handle>) {
2215            $lineCount++;
2216            $line = Strip($line);
2217            push @retVal, $line;
2218        }
2219        # Close it.
2220        close $handle;
2221        my $actualLines = @retVal;
2222        Trace("$actualLines lines read from file $fileName.") if T(File => 2);
2223        # Return the file's contents in the desired format.
2224        if (wantarray) {
2225            return @retVal;
2226          } else {          } else {
2227              $traceMode = "WARN";          return join "\n", @retVal;
2228          }          }
2229      }      }
2230      # Now set up the tracing.  
2231      TSetup("$traceLevel $cats", $traceMode);  =head3 PutFile
2232      # Check for the "h" option. If it is specified, dump the command-line  
2233      # options and exit the program.      Tracer::PutFile($fileName, \@lines);
2234      if ($retOptions->{h}) {  
2235          $0 =~ m#[/\\](\w+)(\.pl)?$#i;  Write out a file from a list of lines of text.
2236          Trace("$1 [options] $parmHelp") if T(0);  
2237          for my $key (sort keys %{$options}) {  =over 4
2238              my $name = Pad($key, $longestName, 0, ' ');  
2239              my $desc = $options->{$key}->[1];  =item fileName
2240              if ($options->{$key}->[0]) {  
2241                  $desc .= " (default " . $options->{$key}->[0] . ")";  Name of the output file.
2242    
2243    =item lines
2244    
2245    Reference to a list of text lines. The lines will be written to the file in order, with trailing
2246    new-line characters. Alternatively, may be a string, in which case the string will be written without
2247    modification.
2248    
2249    =back
2250    
2251    =cut
2252    
2253    sub PutFile {
2254        # Get the parameters.
2255        my ($fileName, $lines) = @_;
2256        # Open the output file.
2257        my $handle = Open(undef, ">$fileName");
2258        # Count the lines written.
2259        if (ref $lines ne 'ARRAY') {
2260            # Here we have a scalar, so we write it raw.
2261            print $handle $lines;
2262            Trace("Scalar put to file $fileName.") if T(File => 3);
2263        } else {
2264            # Write the lines one at a time.
2265            my $count = 0;
2266            for my $line (@{$lines}) {
2267                print $handle "$line\n";
2268                $count++;
2269              }              }
2270              Trace("  $name $desc") if T(0);          Trace("$count lines put to file $fileName.") if T(File => 3);
2271          }          }
2272          exit(0);      # Close the output file.
2273        close $handle;
2274    }
2275    
2276    =head3 ParseRecord
2277    
2278        my @fields = Tracer::ParseRecord($line);
2279    
2280    Parse a tab-delimited data line. The data line is split into field values. Embedded tab
2281    and new-line characters in the data line must be represented as C<\t> and C<\n>, respectively.
2282    These will automatically be converted.
2283    
2284    =over 4
2285    
2286    =item line
2287    
2288    Line of data containing the tab-delimited fields.
2289    
2290    =item RETURN
2291    
2292    Returns a list of the fields found in the data line.
2293    
2294    =back
2295    
2296    =cut
2297    
2298    sub ParseRecord {
2299        # Get the parameter.
2300        my ($line) = @_;
2301        # Remove the trailing new-line, if any.
2302        chomp $line;
2303        # Split the line read into pieces using the tab character.
2304        my @retVal = split /\t/, $line;
2305        # Trim and fix the escapes in each piece.
2306        for my $value (@retVal) {
2307            # Trim leading whitespace.
2308            $value =~ s/^\s+//;
2309            # Trim trailing whitespace.
2310            $value =~ s/\s+$//;
2311            # Delete the carriage returns.
2312            $value =~ s/\r//g;
2313            # Convert the escapes into their real values.
2314            $value =~ s/\\t/"\t"/ge;
2315            $value =~ s/\\n/"\n"/ge;
2316      }      }
2317      # Return the parsed parameters.      # Return the result.
2318      return ($retOptions, @retParameters);      return @retVal;
2319  }  }
2320    
2321  =head3 Setups  =head3 Merge
2322    
2323  C<< my $count = Tracer::Setups(); >>      my @mergedList = Tracer::Merge(@inputList);
2324    
2325  Return the number of times L</TSetup> has been called.  Sort a list of strings and remove duplicates.
2326    
2327  This method allows for the creation of conditional tracing setups where, for example, we  =over 4
2328  may want to set up tracing if nobody else has done it before us.  
2329    =item inputList
2330    
2331    List of scalars to sort and merge.
2332    
2333    =item RETURN
2334    
2335    Returns a list containing the same elements sorted in ascending order with duplicates
2336    removed.
2337    
2338    =back
2339    
2340  =cut  =cut
2341    
2342  sub Setups {  sub Merge {
2343      return $SetupCount;      # Get the input list in sort order.
2344        my @inputList = sort @_;
2345        # Only proceed if the list has at least two elements.
2346        if (@inputList > 1) {
2347            # Now we want to move through the list splicing out duplicates.
2348            my $i = 0;
2349            while ($i < @inputList) {
2350                # Get the current entry.
2351                my $thisEntry = $inputList[$i];
2352                # Find out how many elements duplicate the current entry.
2353                my $j = $i + 1;
2354                my $dup1 = $i + 1;
2355                while ($j < @inputList && $inputList[$j] eq $thisEntry) { $j++; };
2356                # If the number is nonzero, splice out the duplicates found.
2357                if ($j > $dup1) {
2358                    splice @inputList, $dup1, $j - $dup1;
2359                }
2360                # Now the element at position $dup1 is different from the element before it
2361                # at position $i. We push $i forward one position and start again.
2362                $i++;
2363            }
2364        }
2365        # Return the merged list.
2366        return @inputList;
2367  }  }
2368    
2369  =head3 Open  =head3 Open
2370    
2371  C<< my $handle = Open($fileHandle, $fileSpec, $message); >>      my $handle = Open($fileHandle, $fileSpec, $message);
2372    
2373  Open a file.  Open a file.
2374    
# Line 608  Line 2460 
2460    
2461  =head3 FindNamePart  =head3 FindNamePart
2462    
2463  C<< my ($fileName, $start, $len) = Tracer::FindNamePart($fileSpec); >>      my ($fileName, $start, $len) = Tracer::FindNamePart($fileSpec);
2464    
2465  Extract the portion of a file specification that contains the file name.  Extract the portion of a file specification that contains the file name.
2466    
# Line 659  Line 2511 
2511    
2512  =head3 OpenDir  =head3 OpenDir
2513    
2514  C<< my @files = OpenDir($dirName, $filtered, $flag); >>      my @files = OpenDir($dirName, $filtered, $flag);
2515    
2516  Open a directory and return all the file names. This function essentially performs  Open a directory and return all the file names. This function essentially performs
2517  the functions of an C<opendir> and C<readdir>. If the I<$filtered> parameter is  the functions of an C<opendir> and C<readdir>. If the I<$filtered> parameter is
# Line 715  Line 2567 
2567          } else {          } else {
2568              @retVal = readdir $dirHandle;              @retVal = readdir $dirHandle;
2569          }          }
2570            closedir $dirHandle;
2571      } elsif (! $flag) {      } elsif (! $flag) {
2572          # Here the directory would not open and it's considered an error.          # Here the directory would not open and it's considered an error.
2573          Confess("Could not open directory $dirName.");          Confess("Could not open directory $dirName.");
# Line 723  Line 2576 
2576      return @retVal;      return @retVal;
2577  }  }
2578    
 =head3 SetLevel  
2579    
2580  C<< Tracer::SetLevel($newLevel); >>  =head3 Insure
2581    
2582        Insure($dirName, $chmod);
2583    
2584  Modify the trace level. A higher trace level will cause more messages to appear.  Insure a directory is present.
2585    
2586  =over 4  =over 4
2587    
2588  =item newLevel  =item dirName
2589    
2590  Proposed new trace level.  Name of the directory to check. If it does not exist, it will be created.
2591    
2592    =item chmod (optional)
2593    
2594    Security privileges to be given to the directory if it is created.
2595    
2596  =back  =back
2597    
2598  =cut  =cut
2599    
2600  sub SetLevel {  sub Insure {
2601      $TraceLevel = $_[0];      my ($dirName, $chmod) = @_;
2602        if (! -d $dirName) {
2603            Trace("Creating $dirName directory.") if T(2);
2604            eval {
2605                mkpath $dirName;
2606                # If we have permissions specified, set them here.
2607                if (defined($chmod)) {
2608                    chmod $chmod, $dirName;
2609                }
2610            };
2611            if ($@) {
2612                Confess("Error creating $dirName: $@");
2613            }
2614        }
2615  }  }
2616    
2617  =head3 Now  =head3 ChDir
2618    
2619        ChDir($dirName);
2620    
2621    Change to the specified directory.
2622    
2623    =over 4
2624    
2625    =item dirName
2626    
2627  C<< my $string = Tracer::Now(); >>  Name of the directory to which we want to change.
2628    
2629  Return a displayable time stamp containing the local time.  =back
2630    
2631  =cut  =cut
2632    
2633  sub Now {  sub ChDir {
2634      my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);      my ($dirName) = @_;
2635      my $retVal = _p2($mon+1) . "/" . _p2($mday) . "/" . ($year + 1900) . " " .      if (! -d $dirName) {
2636                   _p2($hour) . ":" . _p2($min) . ":" . _p2($sec);          Confess("Cannot change to directory $dirName: no such directory.");
2637      return $retVal;      } else {
2638            Trace("Changing to directory $dirName.") if T(File => 4);
2639            my $okFlag = chdir $dirName;
2640            if (! $okFlag) {
2641                Confess("Error switching to directory $dirName.");
2642            }
2643  }  }
   
 # Pad a number to 2 digits.  
 sub _p2 {  
     my ($value) = @_;  
     $value = "0$value" if ($value < 10);  
     return $value;  
2644  }  }
2645    
2646  =head3 LogErrors  =head3 SetPermissions
2647    
2648  C<< Tracer::LogErrors($fileName); >>      Tracer::SetPermissions($dirName, $group, $mask, %otherMasks);
2649    
2650  Route the standard error output to a log file.  Set the permissions for a directory and all the files and folders inside it.
2651    In addition, the group ownership will be changed to the specified value.
2652    
2653    This method is more vulnerable than most to permission and compatability
2654    problems, so it does internal error recovery.
2655    
2656  =over 4  =over 4
2657    
2658  =item fileName  =item dirName
2659    
2660  Name of the file to receive the error output.  Name of the directory to process.
2661    
2662    =item group
2663    
2664    Name of the group to be assigned.
2665    
2666    =item mask
2667    
2668    Permission mask. Bits that are C<1> in this mask will be ORed into the
2669    permission bits of any file or directory that does not already have them
2670    set to 1.
2671    
2672    =item otherMasks
2673    
2674    Map of search patterns to permission masks. If a directory name matches
2675    one of the patterns, that directory and all its members and subdirectories
2676    will be assigned the new pattern. For example, the following would
2677    assign 0664 to most files, but would use 0777 for directories named C<tmp>.
2678    
2679        Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp$' => 01777);
2680    
2681    The list is ordered, so the following would use 0777 for C<tmp1> and
2682    0666 for C<tmp>, C<tmp2>, or C<tmp3>.
2683    
2684        Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp1' => 0777,
2685                                                       '^tmp' => 0666);
2686    
2687    Note that the pattern matches are all case-insensitive, and only directory
2688    names are matched, not file names.
2689    
2690  =back  =back
2691    
2692  =cut  =cut
2693    
2694  sub LogErrors {  sub SetPermissions {
2695      # Get the file name.      # Get the parameters.
2696      my ($fileName) = @_;      my ($dirName, $group, $mask, @otherMasks) = @_;
2697      # Open the file as the standard error output.      # Set up for error recovery.
2698      open STDERR, '>', $fileName;      eval {
2699            # Switch to the specified directory.
2700            ChDir($dirName);
2701            # Get the group ID.
2702            my $gid = getgrnam($group);
2703            # Get the mask for tracing.
2704            my $traceMask = sprintf("%04o", $mask) . "($mask)";
2705            Trace("Fixing permissions for directory $dirName using group $group($gid) and mask $traceMask.") if T(File => 2);
2706            my $fixCount = 0;
2707            my $lookCount = 0;
2708            # @dirs will be a stack of directories to be processed.
2709            my @dirs = (getcwd());
2710            while (scalar(@dirs) > 0) {
2711                # Get the current directory.
2712                my $dir = pop @dirs;
2713                # Check for a match to one of the specified directory names. To do
2714                # that, we need to pull the individual part of the name off of the
2715                # whole path.
2716                my $simpleName = $dir;
2717                if ($dir =~ m!/([^/]+)$!) {
2718                    $simpleName = $1;
2719                }
2720                Trace("Simple directory name for $dir is $simpleName.") if T(File => 4);
2721                # Search for a match.
2722                my $match = 0;
2723                my $i;
2724                for ($i = 0; $i < $#otherMasks && ! $match; $i += 2) {
2725                    my $pattern = $otherMasks[$i];
2726                    if ($simpleName =~ /$pattern/i) {
2727                        $match = 1;
2728                    }
2729                }
2730                # Find out if we have a match. Note we use $i-1 because the loop added 2
2731                # before terminating due to the match.
2732                if ($match && $otherMasks[$i-1] != $mask) {
2733                    # This directory matches one of the incoming patterns, and it's
2734                    # a different mask, so we process it recursively with that mask.
2735                    SetPermissions($dir, $group, $otherMasks[$i-1], @otherMasks);
2736                } else {
2737                    # Here we can process normally. Get all of the non-hidden members.
2738                    my @submems = OpenDir($dir, 1);
2739                    for my $submem (@submems) {
2740                        # Get the full name.
2741                        my $thisMem = "$dir/$submem";
2742                        Trace("Checking member $thisMem.") if T(4);
2743                        $lookCount++;
2744                        if ($lookCount % 1000 == 0) {
2745                            Trace("$lookCount members examined. Current is $thisMem. Mask is $traceMask") if T(File => 3);
2746                        }
2747                        # Fix the group.
2748                        chown -1, $gid, $thisMem;
2749                        # Insure this member is not a symlink.
2750                        if (! -l $thisMem) {
2751                            # Get its info.
2752                            my $fileInfo = stat $thisMem;
2753                            # Only proceed if we got the info. Otherwise, it's a hard link
2754                            # and we want to skip it anyway.
2755                            if ($fileInfo) {
2756                                my $fileMode = $fileInfo->mode;
2757                                if (($fileMode & $mask) != $mask) {
2758                                    # Fix this member.
2759                                    $fileMode |= $mask;
2760                                    chmod $fileMode, $thisMem;
2761                                    $fixCount++;
2762                                }
2763                                # If it's a subdirectory, stack it.
2764                                if (-d $thisMem) {
2765                                    push @dirs, $thisMem;
2766                                }
2767                            }
2768                        }
2769                    }
2770                }
2771            }
2772            Trace("$lookCount files and directories processed, $fixCount fixed.") if T(File => 2);
2773        };
2774        # Check for an error.
2775        if ($@) {
2776            Confess("SetPermissions error: $@");
2777        }
2778  }  }
2779    
2780  =head3 ReadOptions  =head3 GetLine
   
 C<< my %options = Tracer::ReadOptions($fileName); >>  
   
 Read a set of options from a file. Each option is encoded in a line of text that has the  
 format  
2781    
2782  I<optionName>C<=>I<optionValue>C<; >I<comment>      my @data = Tracer::GetLine($handle);
2783    
2784  The option name must consist entirely of letters, digits, and the punctuation characters  Read a line of data from a tab-delimited file.
 C<.> and C<_>, and is case sensitive. Blank lines and lines in which the first nonblank  
 character is a semi-colon will be ignored. The return hash will map each option name to  
 the corresponding option value.  
2785    
2786  =over 4  =over 4
2787    
2788  =item fileName  =item handle
2789    
2790  Name of the file containing the option data.  Open file handle from which to read.
2791    
2792  =item RETURN  =item RETURN
2793    
2794  Returns a hash mapping the option names specified in the file to their corresponding option  Returns a list of the fields in the record read. The fields are presumed to be
2795  value.  tab-delimited. If we are at the end of the file, then an empty list will be
2796    returned. If an empty line is read, a single list item consisting of a null
2797    string will be returned.
2798    
2799  =back  =back
2800    
2801  =cut  =cut
2802    
2803  sub ReadOptions {  sub GetLine {
2804      # Get the parameters.      # Get the parameters.
2805      my ($fileName) = @_;      my ($handle) = @_;
2806      # Open the file.      # Declare the return variable.
2807      (open CONFIGFILE, "<$fileName") || Confess("Could not open option file $fileName.");      my @retVal = ();
2808      # Count the number of records read.      Trace("File position is " . tell($handle) . ". EOF flag is " . eof($handle) . ".") if T(File => 4);
2809      my ($records, $comments) = 0;      # Read from the file.
2810      # Create the return hash.      my $line = <$handle>;
2811      my %retVal = ();      # Only proceed if we found something.
2812      # Loop through the file, accumulating key-value pairs.      if (defined $line) {
2813      while (my $line = <CONFIGFILE>) {          # Remove the new-line. We are a bit over-cautious here because the file may be coming in via an
2814          # Denote we've read a line.          # upload control and have a nonstandard EOL combination.
2815          $records++;          $line =~ s/(\r|\n)+$//;
2816          # Determine the line type.          # Here we do some fancy tracing to help in debugging complicated EOL marks.
2817          if ($line =~ /^\s*[\n\r]/) {          if (T(File => 4)) {
2818              # A blank line is a comment.              my $escapedLine = $line;
2819              $comments++;              $escapedLine =~ s/\n/\\n/g;
2820          } elsif ($line =~ /^\s*([A-Za-z0-9_\.]+)=([^;]*);/) {              $escapedLine =~ s/\r/\\r/g;
2821              # Here we have an option assignment.              $escapedLine =~ s/\t/\\t/g;
2822              retVal{$1} = $2;              Trace("Line read: -->$escapedLine<--");
2823          } elsif ($line =~ /^\s*;/) {          }
2824              # Here we have a text comment.          # If the line is empty, return a single empty string; otherwise, parse
2825              $comments++;          # it into fields.
2826            if ($line eq "") {
2827                push @retVal, "";
2828          } else {          } else {
2829              # Here we have an invalid line.              push @retVal, split /\t/,$line;
             Trace("Invalid option statement in record $records.") if T(0);  
2830          }          }
2831        } else {
2832            # Trace the reason the read failed.
2833            Trace("End of file: $!") if T(File => 3);
2834      }      }
2835      # Return the hash created.      # Return the result.
2836      return %retVal;      return @retVal;
2837  }  }
2838    
2839  =head3 GetOptions  =head3 PutLine
2840    
2841  C<< Tracer::GetOptions(\%defaults, \%options); >>      Tracer::PutLine($handle, \@fields, $eol);
2842    
2843  Merge a specified set of options into a table of defaults. This method takes two hash references  Write a line of data to a tab-delimited file. The specified field values will be
2844  as input and uses the data from the second to update the first. If the second does not exist,  output in tab-separated form, with a trailing new-line.
 there will be no effect. An error will be thrown if one of the entries in the second hash does not  
 exist in the first.  
2845    
2846  Consider the following example.  =over 4
2847    
2848  C<< my $optionTable = GetOptions({ dbType => 'mySQL', trace => 0 }, $options); >>  =item handle
2849    
2850  In this example, the variable B<$options> is expected to contain at most two options-- B<dbType> and  Output file handle.
 B<trace>. The default database type is C<mySQL> and the default trace level is C<0>. If the value of  
 B<$options> is C<< {dbType => 'Oracle'} >>, then the database type will be changed to C<Oracle> and  
 the trace level will remain at 0. If B<$options> is undefined, then the database type and trace level  
 will remain C<mySQL> and C<0>. If, on the other hand, B<$options> is defined as  
2851    
2852  C<< {databaseType => 'Oracle'} >>  =item fields
2853    
2854  an error will occur because the B<databaseType> option does not exist.  List of field values.
2855    
2856  =over 4  =item eol (optional)
2857    
2858  =item defaults  End-of-line character (default is "\n").
2859    
2860  Table of default option values.  =back
2861    
2862  =item options  =cut
2863    
2864  Table of overrides, if any.  sub PutLine {
2865        # Get the parameters.
2866        my ($handle, $fields, $eol) = @_;
2867        # Write the data.
2868        print $handle join("\t", @{$fields}) . ($eol || "\n");
2869    }
2870    
 =item RETURN  
2871    
2872  Returns a reference to the default table passed in as the first parameter.  =head3 PrintLine
2873    
2874        Tracer::PrintLine($line);
2875    
2876    Print a line of text with a trailing new-line.
2877    
2878    =over 4
2879    
2880    =item line
2881    
2882    Line of text to print.
2883    
2884  =back  =back
2885    
2886  =cut  =cut
2887    
2888  sub GetOptions {  sub PrintLine {
2889      # Get the parameters.      # Get the parameters.
2890      my ($defaults, $options) = @_;      my ($line) = @_;
2891      # Check for overrides.      # Print the line.
2892      if ($options) {      print "$line\n";
         # Loop through the overrides.  
         while (my ($option, $setting) = each %{$options}) {  
             # Insure this override exists.  
             if (!exists $defaults->{$option}) {  
                 croak "Unrecognized option $option encountered.";  
             } else {  
                 # Apply the override.  
                 $defaults->{$option} = $setting;  
             }  
         }  
2893      }      }
2894      # Return the merged table.  
2895      return $defaults;  
2896    =head2 Other Useful Methods
2897    
2898    =head3 IDHASH
2899    
2900        my $hash = SHTargetSearch::IDHASH(@keys);
2901    
2902    This is a dinky little method that converts a list of values to a reference
2903    to hash of values to labels. The values and labels are the same.
2904    
2905    =cut
2906    
2907    sub IDHASH {
2908        my %retVal = map { $_ => $_ } @_;
2909        return \%retVal;
2910  }  }
2911    
2912  =head3 MergeOptions  =head3 Pluralize
2913    
2914  C<< Tracer::MergeOptions(\%table, \%defaults); >>      my $plural = Tracer::Pluralize($word);
2915    
2916  Merge default values into a hash table. This method looks at the key-value pairs in the  This is a very simple pluralization utility. It adds an C<s> at the end
2917  second (default) hash, and if a matching key is not found in the first hash, the default  of the input word unless it already ends in an C<s>, in which case it
2918  pair is copied in. The process is similar to L</GetOptions>, but there is no error-  adds C<es>.
 checking and no return value.  
2919    
2920  =over 4  =over 4
2921    
2922  =item table  =item word
2923    
2924  Hash table to be updated with the default values.  Singular word to pluralize.
2925    
2926  =item defaults  =item RETURN
2927    
2928  Default values to be merged into the first hash table if they are not already present.  Returns the probable plural form of the word.
2929    
2930  =back  =back
2931    
2932  =cut  =cut
2933    
2934  sub MergeOptions {  sub Pluralize {
2935      # Get the parameters.      # Get the parameters.
2936      my ($table, $defaults) = @_;      my ($word) = @_;
2937      # Loop through the defaults.      # Declare the return variable.
2938      while (my ($key, $value) = each %{$defaults}) {      my $retVal;
2939          if (!exists $table->{$key}) {      if ($word =~ /s$/) {
2940              $table->{$key} = $value;          $retVal = $word . 'es';
2941          }      } else {
2942            $retVal = $word . 's';
2943      }      }
2944        # Return the result.
2945        return $retVal;
2946  }  }
2947    
2948  =head3 Trace  =head3 Numeric
2949    
2950  C<< Trace($message); >>      my $okFlag = Tracer::Numeric($string);
2951    
2952  Write a trace message to the target location specified in L</TSetup>. If there has not been  Return the value of the specified string if it is numeric, or an undefined value
2953  any prior call to B<TSetup>.  if it is not numeric.
2954    
2955  =over 4  =over 4
2956    
2957  =item message  =item string
2958    
2959  Message to write.  String to check.
2960    
2961    =item RETURN
2962    
2963    Returns the numeric value of the string if successful, or C<undef> if the string
2964    is not numeric.
2965    
2966  =back  =back
2967    
2968  =cut  =cut
2969    
2970  sub Trace {  sub Numeric {
2971      # Get the parameters.      # Get the parameters.
2972      my ($message) = @_;      my ($string) = @_;
2973      # Get the timestamp.      # We'll put the value in here if we succeed.
2974      my $timeStamp = Now();      my $retVal;
2975      # Format the message. Note we strip off any line terminators at the end.      # Get a working copy of the string.
2976      my $formatted = "$timeStamp <$LastCategory>: " . Strip($message);      my $copy = $string;
2977      # Process according to the destination.      # Trim leading and trailing spaces.
2978      if ($Destination eq "TEXT") {      $copy =~ s/^\s+//;
2979          # Write the message to the standard output.      $copy =~ s/\s+$//;
2980          print "$formatted\n";      # Check the result.
2981      } elsif ($Destination eq "ERROR") {      if ($copy =~ /^[+-]?\d+$/) {
2982          # Write the message to the error output.          $retVal = $copy;
2983          print STDERR "$formatted\n";      } elsif ($copy =~ /^([+-]\d+|\d*)[eE][+-]?\d+$/) {
2984      } elsif ($Destination eq "QUEUE") {          $retVal = $copy;
2985          # Push the message into the queue.      } elsif ($copy =~ /^([+-]\d+|\d*)\.\d*([eE][+-]?\d+)?$/) {
2986          push @Queue, "$formatted";          $retVal = $copy;
     } 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";  
         }  
2987      }      }
2988        # Return the result.
2989        return $retVal;
2990  }  }
2991    
 =head3 T  
   
 C<< my $switch = T($category, $traceLevel); >>  
2992    
2993      or  =head3 ParseParm
2994    
2995  C<< my $switch = T($traceLevel); >>      my $listValue = Tracer::ParseParm($string);
2996    
2997  Return TRUE if the trace level is at or above a specified value and the specified category  Convert a parameter into a list reference. If the parameter is undefined,
2998  is active, else FALSE. If no category is specified, the caller's package name is used.  an undefined value will be returned. Otherwise, it will be parsed as a
2999    comma-separated list of values.
3000    
3001  =over 4  =over 4
3002    
3003  =item category  =item string
   
 Category to which the message belongs. If not specified, the caller's package name is  
 used.  
   
 =item traceLevel  
3004    
3005  Relevant tracing level.  Incoming string.
3006    
3007  =item RETURN  =item RETURN
3008    
3009  TRUE if a message at the specified trace level would appear in the trace, else FALSE.  Returns a reference to a list of values, or C<undef> if the incoming value
3010    was undefined.
3011    
3012  =back  =back
3013    
3014  =cut  =cut
3015    
3016  sub T {  sub ParseParm {
     # Declare the return variable.  
     my $retVal = 0;  
     # Only proceed if tracing is turned on.  
     if ($Destination ne "NONE") {  
3017          # Get the parameters.          # Get the parameters.
3018          my ($category, $traceLevel) = @_;      my ($string) = @_;
3019          if (!defined $traceLevel) {      # Declare the return variable.
3020              # Here we have no category, so we need to get the calling package.      my $retVal;
3021              # The calling package is normally the first parameter. If it is      # Check for data.
3022              # omitted, the first parameter will be the tracelevel. So, the      if (defined $string) {
3023              # first thing we do is shift the so-called category into the          # We have some, so split it into a list.
3024              # $traceLevel variable where it belongs.          $retVal = [ split /\s*,\s*/, $string];
             $traceLevel = $category;  
             my ($package, $fileName, $line) = caller;  
             # If there is no calling package, we default to "main".  
             if (!$package) {  
                 $category = "main";  
             } else {  
                 $category = $package;  
             }  
         }  
         # Save the category name.  
         $LastCategory = $category;  
         # 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.");  
         }  
         $retVal = ($traceLevel <= $TraceLevel && ($AllTrace || exists $Categories{$category}));  
3025      }      }
3026      # Return the computed result.      # Return the result.
3027      return $retVal;      return $retVal;
3028  }  }
3029    
3030  =head3 ParseCommand  =head3 Now
   
 C<< my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList); >>  
   
 Parse a command line consisting of a list of parameters. The initial parameters may be option  
 specifiers of the form C<->I<option> or C<->I<option>C<=>I<value>. The options are stripped  
 off and merged into a table of default options. The remainder of the command line is  
 returned as a list of positional arguments. For example, consider the following invocation.  
   
 C<< my ($options, @arguments) = ParseCommand({ errors => 0, logFile => 'trace.log'}, @words); >>  
3031    
3032  In this case, the list @words will be treated as a command line. There are two options available,      my $string = Tracer::Now();
 B<errors> and B<logFile>. If @words has the following format  
3033    
3034  C<< -logFile=error.log apple orange rutabaga >>  Return a displayable time stamp containing the local time. Whatever format this
3035    method produces must be parseable by L</ParseDate>.
3036    
3037  then at the end of the invocation, C<$options> will be  =cut
3038    
3039  C<< { errors => 0, logFile => 'error.log' } >>  sub Now {
3040        return DisplayTime(time);
3041    }
3042    
3043  and C<@arguments> will contain  =head3 DisplayTime
3044    
3045  C<< apple orange rutabaga >>      my $string = Tracer::DisplayTime($time);
3046    
3047  The parser allows for some escape sequences. See L</UnEscape> for a description. There is no  Convert a time value to a displayable time stamp. Whatever format this
3048  support for quote characters.  method produces must be parseable by L</ParseDate>.
3049    
3050  =over 4  =over 4
3051    
3052  =item optionTable  =item time
   
 Table of default options.  
   
 =item inputList  
3053    
3054  List of words on the command line.  Time to display, in seconds since the epoch, or C<undef> if the time is unknown.
3055    
3056  =item RETURN  =item RETURN
3057    
3058  Returns a reference to the option table and a list of the positional arguments.  Returns a displayable time, or C<(n/a)> if the incoming time is undefined.
   
 =back  
   
 =cut  
3059    
3060  sub ParseCommand {  =back
3061      # Get the parameters.  
3062      my ($optionTable, @inputList) = @_;  =cut
3063      # Process any options in the input list.  
3064      my %overrides = ();  sub DisplayTime {
3065      while ((@inputList > 0) && ($inputList[0] =~ /^-/)) {      my ($time) = @_;
3066          # Get the current option.      my $retVal = "(n/a)";
3067          my $arg = shift @inputList;      if (defined $time) {
3068          # Pull out the option name.          my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time);
3069          $arg =~ /^-([^=]*)/g;          $retVal = _p2($mon+1) . "/" . _p2($mday) . "/" . ($year + 1900) . " " .
3070          my $name = $1;                    _p2($hour) . ":" . _p2($min) . ":" . _p2($sec);
         # Check for an option value.  
         if ($arg =~ /\G=(.*)$/g) {  
             # Here we have a value for the option.  
             $overrides{$name} = UnEscape($1);  
         } else {  
             # Here there is no value, so we use 1.  
             $overrides{$name} = 1;  
         }  
3071      }      }
3072      # Merge the options into the defaults.      return $retVal;
     GetOptions($optionTable, \%overrides);  
     # Translate the remaining parameters.  
     my @retVal = ();  
     for my $inputParm (@inputList) {  
         push @retVal, UnEscape($inputParm);  
3073      }      }
3074      # Return the results.  
3075      return ($optionTable, @retVal);  # Pad a number to 2 digits.
3076    sub _p2 {
3077        my ($value) = @_;
3078        $value = "0$value" if ($value < 10);
3079        return $value;
3080  }  }
3081    
3082  =head3 Escape  =head3 Escape
3083    
3084  C<< my $codedString = Tracer::Escape($realString); >>      my $codedString = Tracer::Escape($realString);
3085    
3086  Escape a string for use in a command length. Tabs will be replaced by C<\t>, new-lines  Escape a string for use in a command. Tabs will be replaced by C<\t>, new-lines
3087  replaced by C<\n>, carriage returns will be deleted, and backslashes will be doubled. The  replaced by C<\n>, carriage returns will be deleted, and backslashes will be doubled. The
3088  result is to reverse the effect of L</UnEscape>.  result is to reverse the effect of L</UnEscape>.
3089    
# Line 1198  Line 3136 
3136    
3137  =head3 UnEscape  =head3 UnEscape
3138    
3139  C<< my $realString = Tracer::UnEscape($codedString); >>      my $realString = Tracer::UnEscape($codedString);
3140    
3141  Replace escape sequences with their actual equivalents. C<\t> will be replaced by  Replace escape sequences with their actual equivalents. C<\t> will be replaced by
3142  a tab, C<\n> by a new-line character, and C<\\> by a backslash. C<\r> codes will  a tab, C<\n> by a new-line character, and C<\\> by a backslash. C<\r> codes will
# Line 1256  Line 3194 
3194      return $retVal;      return $retVal;
3195  }  }
3196    
 =head3 ParseRecord  
   
 C<< my @fields = Tracer::ParseRecord($line); >>  
   
 Parse a tab-delimited data line. The data line is split into field values. Embedded tab  
 and new-line characters in the data line must be represented as C<\t> and C<\n>, respectively.  
 These will automatically be converted.  
   
 =over 4  
   
 =item line  
   
 Line of data containing the tab-delimited fields.  
   
 =item RETURN  
   
 Returns a list of the fields found in the data line.  
   
 =back  
   
 =cut  
   
 sub ParseRecord {  
     # Get the parameter.  
     my ($line) = @_;  
     # Remove the trailing new-line, if any.  
     chomp $line;  
     # Split the line read into pieces using the tab character.  
     my @retVal = split /\t/, $line;  
     # Trim and fix the escapes in each piece.  
     for my $value (@retVal) {  
         # Trim leading whitespace.  
         $value =~ s/^\s+//;  
         # Trim trailing whitespace.  
         $value =~ s/\s+$//;  
         # Delete the carriage returns.  
         $value =~ s/\r//g;  
         # Convert the escapes into their real values.  
         $value =~ s/\\t/"\t"/ge;  
         $value =~ s/\\n/"\n"/ge;  
     }  
     # Return the result.  
     return @retVal;  
 }  
   
 =head3 Merge  
   
 C<< my @mergedList = Tracer::Merge(@inputList); >>  
   
 Sort a list of strings and remove duplicates.  
   
 =over 4  
   
 =item inputList  
   
 List of scalars to sort and merge.  
   
 =item RETURN  
   
 Returns a list containing the same elements sorted in ascending order with duplicates  
 removed.  
   
 =back  
   
 =cut  
   
 sub Merge {  
     # Get the input list in sort order.  
     my @inputList = sort @_;  
     # Only proceed if the list has at least two elements.  
     if (@inputList > 1) {  
         # Now we want to move through the list splicing out duplicates.  
         my $i = 0;  
         while ($i < @inputList) {  
             # Get the current entry.  
             my $thisEntry = $inputList[$i];  
             # Find out how many elements duplicate the current entry.  
             my $j = $i + 1;  
             my $dup1 = $i + 1;  
             while ($j < @inputList && $inputList[$j] eq $thisEntry) { $j++; };  
             # If the number is nonzero, splice out the duplicates found.  
             if ($j > $dup1) {  
                 splice @inputList, $dup1, $j - $dup1;  
             }  
             # Now the element at position $dup1 is different from the element before it  
             # at position $i. We push $i forward one position and start again.  
             $i++;  
         }  
     }  
     # Return the merged list.  
     return @inputList;  
 }  
   
3197  =head3 Percent  =head3 Percent
3198    
3199  C<< my $percent = Tracer::Percent($number, $base); >>      my $percent = Tracer::Percent($number, $base);
3200    
3201  Returns the percent of the base represented by the given number. If the base  Returns the percent of the base represented by the given number. If the base
3202  is zero, returns zero.  is zero, returns zero.
# Line 1377  Line 3222 
3222  sub Percent {  sub Percent {
3223      # Get the parameters.      # Get the parameters.
3224      my ($number, $base) = @_;      my ($number, $base) = @_;
3225      # Declare the return variable.      # Declare the return variable.
3226      my $retVal = 0;      my $retVal = 0;
3227      # Compute the percent.      # Compute the percent.
3228      if ($base != 0) {      if ($base != 0) {
3229          $retVal = $number * 100 / $base;          $retVal = $number * 100 / $base;
3230      }      }
3231      # Return the result.      # Return the result.
3232      return $retVal;      return $retVal;
3233  }  }
   
 =head3 GetFile  
   
 C<< my @fileContents = Tracer::GetFile($fileName); >>  
   
     or  
   
 C<< my $fileContents = Tracer::GetFile($fileName); >>  
   
 Return the entire contents of a file. In list context, line-ends are removed and  
 each line is a list element. In scalar context, line-ends are replaced by C<\n>.  
   
 =over 4  
   
 =item fileName  
   
 Name of the file to read.  
   
 =item RETURN  
   
 In a list context, returns the entire file as a list with the line terminators removed.  
 In a scalar context, returns the entire file as a string. If an error occurs opening  
 the file, an empty list will be returned.  
   
 =back  
   
 =cut  
   
 sub GetFile {  
     # Get the parameters.  
     my ($fileName) = @_;  
     # Declare the return variable.  
     my @retVal = ();  
     # Open the file for input.  
     my $handle = Open(undef, "<$fileName");  
     # Read the whole file into the return variable, stripping off any terminator  
     # characters.  
     my $lineCount = 0;  
     while (my $line = <$handle>) {  
         $lineCount++;  
         $line = Strip($line);  
         push @retVal, $line;  
     }  
     # Close it.  
     close $handle;  
     my $actualLines = @retVal;  
     # Return the file's contents in the desired format.  
     if (wantarray) {  
         return @retVal;  
     } else {  
         return join "\n", @retVal;  
     }  
 }  
   
 =head3 PutFile  
   
 C<< Tracer::PutFile($fileName, \@lines); >>  
   
 Write out a file from a list of lines of text.  
   
 =over 4  
   
 =item fileName  
   
 Name of the output file.  
   
 =item lines  
   
 Reference to a list of text lines. The lines will be written to the file in order, with trailing  
 new-line characters.  
   
 =back  
   
 =cut  
   
 sub PutFile {  
     # Get the parameters.  
     my ($fileName, $lines) = @_;  
     # Open the output file.  
     my $handle = Open(undef, ">$fileName");  
     # Write the lines.  
     for my $line (@{$lines}) {  
         print $handle "$line\n";  
     }  
     # Close the output file.  
     close $handle;  
 }  
   
 =head3 QTrace  
   
 C<< my $data = QTrace($format); >>  
   
 Return the queued trace data in the specified format.  
   
 =over 4  
   
 =item format  
   
 C<html> to format the data as an HTML list, C<text> to format it as straight text.  
   
 =back  
   
 =cut  
   
 sub QTrace {  
     # Get the parameter.  
     my ($format) = @_;  
     # Create the return variable.  
     my $retVal = "";  
     # Only proceed if there is an actual queue.  
     if (@Queue) {  
         # Process according to the format.  
         if ($format =~ m/^HTML$/i) {  
             # Convert the queue into an HTML list.  
             $retVal = "<ul>\n";  
             for my $line (@Queue) {  
                 my $escapedLine = CGI::escapeHTML($line);  
                 $retVal .= "<li>$escapedLine</li>\n";  
             }  
             $retVal .= "</ul>\n";  
         } elsif ($format =~ m/^TEXT$/i) {  
             # Convert the queue into a list of text lines.  
             $retVal = join("\n", @Queue) . "\n";  
         }  
         # Clear the queue.  
         @Queue = ();  
     }  
     # Return the formatted list.  
     return $retVal;  
 }  
   
 =head3 Confess  
   
 C<< Confess($message); >>  
   
 Trace the call stack and abort the program with the specified message. When used with  
 the OR operator and the L</Assert> method, B<Confess> can function 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.  
   
 =over 4  
3234    
3235  =item message  =head3 In
3236    
3237  Message to include in the trace.      my $flag = Tracer::In($value, $min, $max);
3238    
3239  =back  Return TRUE if the value is between the minimum and the maximum, else FALSE.
3240    
3241  =cut  =cut
3242    
3243  sub Confess {  sub In {
3244      # Get the parameters.      return ($_[0] <= $_[2] && $_[0] >= $_[1]);
     my ($message) = @_;  
     # Trace the call stack.  
     Cluck($message);  
     # Abort the program.  
     croak(">>> $message");  
3245  }  }
3246    
 =head3 Assert  
   
 C<< Assert($condition1, $condition2, ... $conditionN); >>  
3247    
3248  Return TRUE if all the conditions are true. This method can be used in conjunction with  =head3 Constrain
 the OR operator and the L</Confess> method as a debugging assert.  
 So, for example  
3249    
3250  C<< Assert($recNum >= 0) || Confess("Invalid record number $recNum."); >>      my $constrained = Constrain($value, $min, $max);
3251    
3252  Will abort the program with a stack trace if the value of C<$recNum> is negative.  Modify a numeric value to bring it to a point in between a maximum and a minimum.
3253    
3254  =cut  =over 4
 sub Assert {  
     my $retVal = 1;  
     LOOP: for my $condition (@_) {  
         if (! $condition) {  
             $retVal = 0;  
             last LOOP;  
         }  
     }  
     return $retVal;  
 }  
3255    
3256  =head3 Cluck  =item value
3257    
3258  C<< Cluck($message); >>  Value to constrain.
3259    
3260  Trace the call stack. Note that for best results, you should qualify the call with a  =item min (optional)
 trace condition. For example,  
3261    
3262  C<< Cluck("Starting record parse.") if T(3); >>  Minimum permissible value. If this parameter is undefined, no minimum constraint will be applied.
3263    
3264  will only trace the stack if the trace level for the package is 3 or more.  =item max (optional)
3265    
3266  =over 4  Maximum permissible value. If this parameter is undefined, no maximum constraint will be applied.
3267    
3268  =item message  =item RETURN
3269    
3270  Message to include in the trace.  Returns the incoming value, constrained according to the other parameters.
3271    
3272  =back  =back
3273    
3274  =cut  =cut
3275    
3276  sub Cluck {  sub Constrain {
3277      # Get the parameters.      # Get the parameters.
3278      my ($message) = @_;      my ($value, $min, $max) = @_;
3279      # Trace what's happening.      # Declare the return variable.
3280      Trace("Stack trace for event: $message");      my $retVal = $value;
3281      my $confession = longmess($message);      # Apply the minimum constraint.
3282      # Convert the confession to a series of trace messages. Note we skip any      if (defined $min && $retVal < $min) {
3283      # messages relating to calls into Tracer.          $retVal = $min;
3284      for my $line (split /\s*\n/, $confession) {      }
3285          Trace($line) if ($line !~ /Tracer\.pm/);      # Apply the maximum constraint.
3286        if (defined $max && $retVal > $max) {
3287            $retVal = $max;
3288      }      }
3289        # Return the result.
3290        return $retVal;
3291  }  }
3292    
3293  =head3 Min  =head3 Min
3294    
3295  C<< my $min = Min($value1, $value2, ... $valueN); >>      my $min = Min($value1, $value2, ... $valueN);
3296    
3297  Return the minimum argument. The arguments are treated as numbers.  Return the minimum argument. The arguments are treated as numbers.
3298    
# Line 1641  Line 3325 
3325    
3326  =head3 Max  =head3 Max
3327    
3328  C<< my $max = Max($value1, $value2, ... $valueN); >>      my $max = Max($value1, $value2, ... $valueN);
3329    
3330  Return the maximum argument. The arguments are treated as numbers.  Return the maximum argument. The arguments are treated as numbers.
3331    
# Line 1672  Line 3356 
3356      return $retVal;      return $retVal;
3357  }  }
3358    
3359  =head3 AddToListMap  =head3 Strip
3360    
3361  C<< Tracer::AddToListMap(\%hash, $key, $value1, $value2, ... valueN); >>      my $string = Tracer::Strip($line);
3362    
3363  Add a key-value pair to a hash of lists. If no value exists for the key, a singleton list  Strip all line terminators off a string. This is necessary when dealing with files
3364  is created for the key. Otherwise, the new value is pushed onto the list.  that may have been transferred back and forth several times among different
3365    operating environments.
3366    
3367  =over 4  =over 4
3368    
3369  =item hash  =item line
   
 Reference to the target hash.  
   
 =item key  
3370    
3371  Key for which the value is to be added.  Line of text to be stripped.
3372    
3373  =item value1, value2, ... valueN  =item RETURN
3374    
3375  List of values to add to the key's value list.  The same line of text with all the line-ending characters chopped from the end.
3376    
3377  =back  =back
3378    
3379  =cut  =cut
3380    
3381  sub AddToListMap {  sub Strip {
3382      # Get the parameters.      # Get a copy of the parameter string.
3383      my ($hash, $key, @values) = @_;      my ($string) = @_;
3384      # Process according to whether or not the key already has a value.      my $retVal = (defined $string ? $string : "");
3385      if (! exists $hash->{$key}) {      # Strip the line terminator characters.
3386          $hash->{$key} = [@values];      $retVal =~ s/(\r|\n)+$//g;
3387      } else {      # Return the result.
         push @{$hash->{$key}}, @values;  
     }  
 }  
   
 =head3 DebugMode  
   
 C<< if (Tracer::DebugMode) { ...code... } >>  
   
 Return TRUE if debug mode has been turned on, else output an error  
 page and return FALSE.  
   
 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 web page will be output directing the  
 user to enter in the correct password.  
   
 =cut  
   
 sub DebugMode {  
     # Declare the return variable.  
     my $retVal = 0;  
     # Check the debug configuration.  
     my $password = CGI::cookie("DebugMode");  
     my $encrypted = Digest::MD5::md5_hex($password);  
     if ($encrypted eq "252dec43280e0c0d6a75ffcec486e61d") {  
         $retVal = 1;  
     } else {  
         # Here debug mode is off, so we generate an error page.  
         my $pageString = PageBuilder::Build("<<Html/ErrorPage.html", {}, "Html");  
         print $pageString;  
     }  
     # Return the determination indicator.  
3388      return $retVal;      return $retVal;
3389  }  }
3390    
3391  =head3 Strip  =head3 Trim
3392    
3393  C<< my $string = Tracer::Strip($line); >>      my $string = Tracer::Trim($line);
3394    
3395  Strip all line terminators off a string. This is necessary when dealing with files  Trim all spaces from the beginning and ending of a string.
 that may have been transferred back and forth several times among different  
 operating environments.  
3396    
3397  =over 4  =over 4
3398    
3399  =item line  =item line
3400    
3401  Line of text to be stripped.  Line of text to be trimmed.
3402    
3403  =item RETURN  =item RETURN
3404    
3405  The same line of text with all the line-ending characters chopped from the end.  The same line of text with all whitespace chopped off either end.
3406    
3407  =back  =back
3408    
3409  =cut  =cut
3410    
3411  sub Strip {  sub Trim {
3412      # Get a copy of the parameter string.      # Get a copy of the parameter string.
3413      my ($string) = @_;      my ($string) = @_;
3414      my $retVal = (defined $string ? $string : "");      my $retVal = (defined $string ? $string : "");
3415      # Strip the line terminator characters.      # Strip the front spaces.
3416      $retVal =~ s/(\r|\n)+$//g;      $retVal =~ s/^\s+//;
3417        # Strip the back spaces.
3418        $retVal =~ s/\s+$//;
3419      # Return the result.      # Return the result.
3420      return $retVal;      return $retVal;
3421  }  }
3422    
3423  =head3 Pad  =head3 Pad
3424    
3425  C<< my $paddedString = Tracer::Pad($string, $len, $left, $padChar); >>      my $paddedString = Tracer::Pad($string, $len, $left, $padChar);
3426    
3427  Pad a string to a specified length. The pad character will be a  Pad a string to a specified length. The pad character will be a
3428  space, and the padding will be on the right side unless specified  space, and the padding will be on the right side unless specified
# Line 1834  Line 3481 
3481      return $retVal;      return $retVal;
3482  }  }
3483    
3484    =head3 Quoted
3485    
3486        my $string = Tracer::Quoted($var);
3487    
3488    Convert the specified value to a string and enclose it in single quotes.
3489    If it's undefined, the string C<undef> in angle brackets will be used
3490    instead.
3491    
3492    =over 4
3493    
3494    =item var
3495    
3496    Value to quote.
3497    
3498    =item RETURN
3499    
3500    Returns a string enclosed in quotes, or an indication the value is undefined.
3501    
3502    =back
3503    
3504    =cut
3505    
3506    sub Quoted {
3507        # Get the parameters.
3508        my ($var) = @_;
3509        # Declare the return variable.
3510        my $retVal;
3511        # Are we undefined?
3512        if (! defined $var) {
3513            $retVal = "<undef>";
3514        } else {
3515            # No, so convert to a string and enclose in quotes.
3516            $retVal = $var;
3517            $retVal =~ s/'/\\'/;
3518            $retVal = "'$retVal'";
3519        }
3520        # Return the result.
3521        return $retVal;
3522    }
3523    
3524  =head3 EOF  =head3 EOF
3525    
3526  This is a constant that is lexically greater than any useful string.  This is a constant that is lexically greater than any useful string.
# Line 1846  Line 3533 
3533    
3534  =head3 TICK  =head3 TICK
3535    
3536  C<< my @results = TICK($commandString); >>      my @results = TICK($commandString);
3537    
3538  Perform a back-tick operation on a command. If this is a Windows environment, any leading  Perform a back-tick operation on a command. If this is a Windows environment, any leading
3539  dot-slash (C<./> will be removed. So, for example, if you were doing  dot-slash (C<./> will be removed. So, for example, if you were doing
# Line 1885  Line 3572 
3572      return `$commandString`;      return `$commandString`;
3573  }  }
3574    
 =head3 ScriptSetup  
3575    
3576  C<< my ($query, $varHash) = ScriptSetup(); >>  =head3 CommaFormat
3577    
3578        my $formatted = Tracer::CommaFormat($number);
3579    
3580  Perform standard tracing and debugging setup for scripts. The value returned is  Insert commas into a number.
3581  the CGI object followed by a pre-built variable hash.  
3582    =over 4
3583    
3584    =item number
3585    
3586    A sequence of digits.
3587    
3588    =item RETURN
3589    
3590    Returns the same digits with commas strategically inserted.
3591    
3592  The C<Trace> query parameter is used to determine whether or not tracing is active and  =back
 which trace modules (other than C<Tracer> and C<FIG>) 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. At the end of the script, the  
 client should call L</ScriptFinish> to output the web page.  
3593    
3594  =cut  =cut
3595    
3596  sub ScriptSetup {  sub CommaFormat {
3597      # Get the CGI query object.      # Get the parameters.
3598      my $query = CGI->new();      my ($number) = @_;
3599      # Check for tracing. Set it up if the user asked for it.      # Pad the length up to a multiple of three.
3600      if ($query->param('Trace')) {      my $padded = "$number";
3601          # Set up tracing to be queued for display at the bottom of the web page.      $padded = " " . $padded while length($padded) % 3 != 0;
3602          TSetup($query->param('Trace') . " FIG Tracer", "QUEUE");      # This is a fancy PERL trick. The parentheses in the SPLIT pattern
3603          # Trace the parameter and environment data.      # cause the delimiters to be included in the output stream. The
3604          if (T(CGI => 3)) {      # GREP removes the empty strings in between the delimiters.
3605              # Here we want to trace the parameter data.      my $retVal = join(",", grep { $_ ne '' } split(/(...)/, $padded));
3606              my @names = $query->param;      # Clean out the spaces.
3607              for my $parmName (sort @names) {      $retVal =~ s/ //g;
3608                  # Note we skip "Trace", which is for our use only.      # Return the result.
3609                  if ($parmName ne 'Trace') {      return $retVal;
                     my @values = $query->param($parmName);  
                     Trace("CGI: $parmName = " . join(", ", @values));  
3610                  }                  }
3611    
3612    
3613    =head3 GetMemorySize
3614    
3615        my $string = Tracer::GetMemorySize();
3616    
3617    Return a memory size string for the current process. The string will be
3618    in comma format, with a size indicator (K, M, G) at the end.
3619    
3620    =cut
3621    
3622    sub GetMemorySize {
3623        # Get the memory size from Unix.
3624        my ($retVal) = `ps h -o vsz $$`;
3625        # Remove the ending new-line.
3626        chomp $retVal;
3627        # Format and return the result.
3628        return CommaFormat($retVal) . "K";
3629              }              }
3630    
3631    =head3 CompareLists
3632    
3633        my ($inserted, $deleted) = Tracer::CompareLists(\@newList, \@oldList, $keyIndex);
3634    
3635    Compare two lists of tuples, and return a hash analyzing the differences. The lists
3636    are presumed to be sorted alphabetically by the value in the $keyIndex column.
3637    The return value contains a list of items that are only in the new list
3638    (inserted) and only in the old list (deleted).
3639    
3640    =over 4
3641    
3642    =item newList
3643    
3644    Reference to a list of new tuples.
3645    
3646    =item oldList
3647    
3648    Reference to a list of old tuples.
3649    
3650    =item keyIndex (optional)
3651    
3652    Index into each tuple of its key field. The default is 0.
3653    
3654    =item RETURN
3655    
3656    Returns a 2-tuple consisting of a reference to the list of items that are only in the new
3657    list (inserted) followed by a reference to the list of items that are only in the old
3658    list (deleted).
3659    
3660    =back
3661    
3662    =cut
3663    
3664    sub CompareLists {
3665        # Get the parameters.
3666        my ($newList, $oldList, $keyIndex) = @_;
3667        if (! defined $keyIndex) {
3668            $keyIndex = 0;
3669        }
3670        # Declare the return variables.
3671        my ($inserted, $deleted) = ([], []);
3672        # Loop through the two lists simultaneously.
3673        my ($newI, $oldI) = (0, 0);
3674        my ($newN, $oldN) = (scalar @{$newList}, scalar @{$oldList});
3675        while ($newI < $newN || $oldI < $oldN) {
3676            # Get the current object in each list. Note that if one
3677            # of the lists is past the end, we'll get undef.
3678            my $newItem = $newList->[$newI];
3679            my $oldItem = $oldList->[$oldI];
3680            if (! defined($newItem) || defined($oldItem) && $newItem->[$keyIndex] gt $oldItem->[$keyIndex]) {
3681                # The old item is not in the new list, so mark it deleted.
3682                push @{$deleted}, $oldItem;
3683                $oldI++;
3684            } elsif (! defined($oldItem) || $oldItem->[$keyIndex] gt $newItem->[$keyIndex]) {
3685                # The new item is not in the old list, so mark it inserted.
3686                push @{$inserted}, $newItem;
3687                $newI++;
3688            } else {
3689                # The item is in both lists, so push forward.
3690                $oldI++;
3691                $newI++;
3692          }          }
         if (T(CGI => 4)) {  
             # Here we want the environment data too.  
             for my $envName (sort keys %ENV) {  
                 Trace("ENV: $envName = $ENV{$envName}");  
3693              }              }
3694        # Return the result.
3695        return ($inserted, $deleted);
3696          }          }
3697    
3698    =head3 Cmp
3699    
3700        my $cmp = Tracer::Cmp($a, $b);
3701    
3702    This method performs a universal sort comparison. Each value coming in is
3703    separated into a text parts and number parts. The text
3704    part is string compared, and if both parts are equal, then the number
3705    parts are compared numerically. A stream of just numbers or a stream of
3706    just strings will sort correctly, and a mixed stream will sort with the
3707    numbers first. Strings with a label and a number will sort in the
3708    expected manner instead of lexically. Undefined values sort last.
3709    
3710    =over 4
3711    
3712    =item a
3713    
3714    First item to compare.
3715    
3716    =item b
3717    
3718    Second item to compare.
3719    
3720    =item RETURN
3721    
3722    Returns a negative number if the first item should sort first (is less), a positive
3723    number if the first item should sort second (is greater), and a zero if the items are
3724    equal.
3725    
3726    =back
3727    
3728    =cut
3729    
3730    sub Cmp {
3731        # Get the parameters.
3732        my ($a, $b) = @_;
3733        # Declare the return value.
3734        my $retVal;
3735        # Check for nulls.
3736        if (! defined($a)) {
3737            $retVal = (! defined($b) ? 0 : -1);
3738        } elsif (! defined($b)) {
3739            $retVal = 1;
3740      } else {      } else {
3741          # Here tracing is to be turned off. All we allow is errors traced into the          # Here we have two real values. Parse the two strings.
3742          # error log.          my @aParsed = _Parse($a);
3743          TSetup("0", "WARN");          my @bParsed = _Parse($b);
3744            # Loop through the first string.
3745            while (! $retVal && @aParsed) {
3746                # Extract the string parts.
3747                my $aPiece = shift(@aParsed);
3748                my $bPiece = shift(@bParsed) || '';
3749                # Extract the number parts.
3750                my $aNum = shift(@aParsed);
3751                my $bNum = shift(@bParsed) || 0;
3752                # Compare the string parts insensitively.
3753                $retVal = (lc($aPiece) cmp lc($bPiece));
3754                # If they're equal, compare them sensitively.
3755                if (! $retVal) {
3756                    $retVal = ($aPiece cmp $bPiece);
3757                    # If they're STILL equal, compare the number parts.
3758                    if (! $retVal) {
3759                        $retVal = $aNum <=> $bNum;
3760                    }
3761                }
3762            }
3763        }
3764        # Return the result.
3765        return $retVal;
3766    }
3767    
3768    # This method parses an input string into a string parts alternating with
3769    # number parts.
3770    sub _Parse {
3771        # Get the incoming string.
3772        my ($string) = @_;
3773        # The pieces will be put in here.
3774        my @retVal;
3775        # Loop through as many alpha/num sets as we can.
3776        while ($string =~ /^(\D*)(\d+)(.*)/) {
3777            # Push the alpha and number parts into the return string.
3778            push @retVal, $1, $2;
3779            # Save the residual.
3780            $string = $3;
3781        }
3782        # If there's still stuff left, add it to the end with a trailing
3783        # zero.
3784        if ($string) {
3785            push @retVal, $string, 0;
3786        }
3787        # Return the list.
3788        return @retVal;
3789    }
3790    
3791    =head3 ListEQ
3792    
3793        my $flag = Tracer::ListEQ(\@a, \@b);
3794    
3795    Return TRUE if the specified lists contain the same strings in the same
3796    order, else FALSE.
3797    
3798    =over 4
3799    
3800    =item a
3801    
3802    Reference to the first list.
3803    
3804    =item b
3805    
3806    Reference to the second list.
3807    
3808    =item RETURN
3809    
3810    Returns TRUE if the two parameters are identical string lists, else FALSE.
3811    
3812    =back
3813    
3814    =cut
3815    
3816    sub ListEQ {
3817        # Get the parameters.
3818        my ($a, $b) = @_;
3819        # Declare the return variable. Start by checking the lengths.
3820        my $n = scalar(@$a);
3821        my $retVal = ($n == scalar(@$b));
3822        # Now compare the list elements.
3823        for (my $i = 0; $retVal && $i < $n; $i++) {
3824            $retVal = ($a->[$i] eq $b->[$i]);
3825        }
3826        # Return the result.
3827        return $retVal;
3828      }      }
3829    
3830    =head2 CGI Script Utilities
3831    
3832    =head3 ScriptSetup (deprecated)
3833    
3834        my ($cgi, $varHash) = ScriptSetup($noTrace);
3835    
3836    Perform standard tracing and debugging setup for scripts. The value returned is
3837    the CGI object followed by a pre-built variable hash. At the end of the script,
3838    the client should call L</ScriptFinish> to output the web page.
3839    
3840    This method calls L</ETracing> to configure tracing, which allows the tracing
3841    to be configured via the emergency tracing form on the debugging control panel.
3842    Tracing will then be turned on automatically for all programs that use the L</ETracing>
3843    method, which includes every program that uses this method or L</StandardSetup>.
3844    
3845    =over 4
3846    
3847    =item noTrace (optional)
3848    
3849    If specified, tracing will be suppressed. This is useful if the script wants to set up
3850    tracing manually.
3851    
3852    =item RETURN
3853    
3854    Returns a two-element list consisting of a CGI query object and a variable hash for
3855