[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.69, Mon Oct 2 02:59:47 2006 UTC revision 1.97, Tue Apr 29 06:01:21 2008 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    
21      require Exporter;      require Exporter;
22      @ISA = ('Exporter');      @ISA = ('Exporter');
23      @EXPORT = qw(Trace T TSetup QTrace Confess Cluck Min Max Assert Open OpenDir TICK StandardSetup EmergencyIP ScriptSetup ScriptFinish Insure ChDir Emergency);      @EXPORT = qw(Trace T TSetup QTrace Confess Cluck Min Max Assert Open OpenDir TICK StandardSetup EmergencyKey ETracing Constrain Insure ChDir Emergency);
24      @EXPORT_OK = qw(GetFile GetOptions Merge MergeOptions ParseCommand ParseRecord UnEscape Escape);      @EXPORT_OK = qw(GetFile GetOptions Merge MergeOptions ParseCommand ParseRecord UnEscape Escape PrintLine PutLine);
25      use strict;      use strict;
26      use Carp qw(longmess croak);      use Carp qw(longmess croak carp);
27      use CGI;      use CGI;
28      use Cwd;      use Cwd;
29      use FIG_Config;      use FIG_Config;
# Line 34  Line 35 
35      use LWP::UserAgent;      use LWP::UserAgent;
36      use Time::HiRes 'gettimeofday';      use Time::HiRes 'gettimeofday';
37      use URI::Escape;      use URI::Escape;
38        use Time::Local;
39    
40  =head1 Tracing and Debugging Helpers  =head1 Tracing and Debugging Helpers
41    
42  =head2 Introduction  =head2 Tracing
43    
44  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
45  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.
46  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,
47  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
48  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
49  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
50  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
51  appear. To generate a trace message, use the following syntax.  appear.
52    
53    =head3 Putting Trace Messages in Your Code
54    
55    To generate a trace message, use the following syntax.
56    
57  C<< Trace($message) if T(errors => 4); >>      Trace($message) if T(errors => 4);
58    
59  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>
60  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
61    
62  C<< Trace($message) if T(main => 4); >>      Trace($message) if T(main => 4);
63    
64  will trace if the trace level is 4 or more.  will trace if the trace level is 4 or more.
65    
# Line 61  Line 67 
67  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
68  active and the trace level is 2 or more.  active and the trace level is 2 or more.
69    
70  C<< Trace($message) if T(2); >>      Trace($message) if T(2);
71    
72  To set up tracing, you call the L</TSetup> method. The method takes as input a trace level, a list  In scripts, where no package name is available, the category defaults to C<main>.
73  of category names, and a set of options. The trace level and list of category names are  
74    =head3 Custom Tracing
75    
76    Many programs have customized tracing configured using the L</TSetup> method. This is no longer
77    the preferred method, but a knowledge of how custom tracing works can make the more modern
78    L</Emergency Tracing> easier to understand.
79    
80    To set up custom tracing, you call the L</TSetup> method. The method takes as input a trace level,
81    a list of category names, and a destination. The trace level and list of category names are
82  specified as a space-delimited string. Thus  specified as a space-delimited string. Thus
83    
84  C<< TSetup('3 errors Sprout ERDB', 'HTML'); >>      TSetup('3 errors Sprout ERDB', 'TEXT');
85    
86  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
87  specifies that messages should be output as HTML paragraphs.  specifies that messages should be sent to the standard output.
88    
89  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
90  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
91  useful in a CGI environment.  useful in a CGI environment.
92    
93  C<< TSetup('3 *', 'WARN'); >>      TSetup('3 *', 'WARN');
94    
95  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
96  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
97  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
98  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
99  it easier to debug page formatting problems.  it easier to debug page formatting problems.
100    
101  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
102    a file at the same time. To trace to a file, specify the filename with an output character in front
103    of it.
104    
105        TSetup('4 SQL', ">$fileName");
106    
107    To trace to the standard output and a file at the same time, put a C<+> in front of the angle
108    bracket.
109    
110        TSetup('3 *', "+>$fileName");
111    
112  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>.
113  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.
114  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
115  being used out in the field.  being used out in the field.
116    
117    =head3 Trace Levels
118    
119  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
120  a suggestion.  a suggestion.
121    
# Line 122  Line 147 
147  =back  =back
148    
149  The format of trace messages is important because some utilities analyze trace files.  The format of trace messages is important because some utilities analyze trace files.
150  The time stamp is between square brackets, the module name between angle brackets,  There are three fields-- the time stamp, the category name, and the text.
151  a colon (C<:>), and the message text after that. If the square brackets or angle  The time stamp is between square brackets and the category name between angle brackets.
152  brackets are missing, then the trace management utilities assume that they  After the category name there is a colon (C<:>) followed by the message text.
153  are encountering a set of pre-formatted lines.  If the square brackets or angle brackets are missing, then the trace management
154    utilities assume that they are encountering a set of pre-formatted lines.
155    
156    Note, however, that this formatting is done automatically by the tracing functions. You
157    only need to know about it if you want to parse a trace file.
158    
159    =head3 Emergency Tracing
160    
161    Sometimes, you need a way for tracing to happen automatically without putting parameters
162    in a form or on the command line. Emergency tracing does this. You invoke emergency tracing
163    from the debug form, which is accessed from the [[DebugConsole]]. Emergency tracing requires
164    that you specify a tracing key. For command-line tools, the key is
165    taken from the C<TRACING> environment variable. For web services, the key is taken from
166    a cookie. Either way, the key tells the tracing facility who you are, so that you control
167    the tracing in your environment without stepping on other users.
168    
169    The key can be anything you want. If you don't have a key, the C<SetPassword> page will
170    generate one for you.
171    
172    You can activate and de-activate emergency tracing from the debugging control panel, as
173    well as display the trace file itself.
174    
175    To enable emergency tracing in your code, call
176    
177        ETracing($cgi)
178    
179    from a web script and
180    
181        ETracing()
182    
183    from a command-line script.
184    
185    The web script will look for the tracing key in the cookies, and the command-line
186    script will look for it in the C<TRACING> environment variable. If you are
187    using the L</StandardSetup> method or a [[WebApplication]], emergency tracing
188    will be configured automatically.
189    
190  =cut  =cut
191    
192  # Declare the configuration variables.  # Declare the configuration variables.
193    
194  my $Destination = "NONE";   # Description of where to send the trace output.  my $Destination = "WARN";   # Description of where to send the trace output.
195  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
196                              # standard output                              # standard output
197  my %Categories = ( main => 1 );  my %Categories = ( main => 1 );
198                              # hash of active category names                              # hash of active category names
199    my @LevelNames = qw(error warn notice info detail);
200  my $TraceLevel = 0;         # trace level; a higher trace level produces more  my $TraceLevel = 0;         # trace level; a higher trace level produces more
201                              # messages                              # messages
202  my @Queue = ();             # queued list of trace messages.  my @Queue = ();             # queued list of trace messages.
203  my $LastCategory = "main";  # name of the last category interrogated  my $LastCategory = "main";  # name of the last category interrogated
204    my $LastLevel = 0;          # level of the last test call
205  my $SetupCount = 0;         # number of times TSetup called  my $SetupCount = 0;         # number of times TSetup called
206  my $AllTrace = 0;           # TRUE if we are tracing all categories.  my $AllTrace = 0;           # TRUE if we are tracing all categories.
207    
208  =head2 Public Methods  =head2 Tracing Methods
209    
210    =head3 Setups
211    
212        my $count = Tracer::Setups();
213    
214    Return the number of times L</TSetup> has been called.
215    
216    This method allows for the creation of conditional tracing setups where, for example, we
217    may want to set up tracing if nobody else has done it before us.
218    
219    =cut
220    
221    sub Setups {
222        return $SetupCount;
223    }
224    
225  =head3 TSetup  =head3 TSetup
226    
227  C<< TSetup($categoryList, $target); >>      TSetup($categoryList, $target);
228    
229  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
230  and interrogated by the L</Trace> and L</T> methods.  and interrogated by the L</Trace> and L</T> methods.
# Line 206  Line 283 
283          }          }
284          if ($target =~ m/^>[^>]/) {          if ($target =~ m/^>[^>]/) {
285              open TRACEFILE, $target;              open TRACEFILE, $target;
286              print TRACEFILE "[" . Now() . "] <Tracer>: Tracing initialized.\n";              print TRACEFILE "[" . Now() . "] [Tracer] Tracing initialized.\n";
287              close TRACEFILE;              close TRACEFILE;
288              $Destination = ">$target";              $Destination = ">$target";
289          } else {          } else {
# Line 219  Line 296 
296      $SetupCount++;      $SetupCount++;
297  }  }
298    
299  =head3 StandardSetup  =head3 SetLevel
300    
301  C<< my ($options, @parameters) = StandardSetup(\@categories, \%options, $parmHelp, @ARGV); >>      Tracer::SetLevel($newLevel);
302    
303  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.  
304    
305  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.  
306    
307  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  
308    
309      ["Sprout", "SproutLoad", "ERDB"]  Proposed new trace level.
310    
311  This would cause trace messages in the specified three packages to appear in  =back
 the output. There are two special tracing categories that are automatically  
 handled by this method. In other words, if you used L</TSetup> you would need  
 to include these categories manually, but if you use this method they are turned  
 on automatically.  
312    
313  =over 4  =cut
314    
315  =item SQL  sub SetLevel {
316        $TraceLevel = $_[0];
317    }
318    
319  Traces SQL commands and activity.  =head3 ParseDate
320    
321  =item Tracer      my $time = Tracer::ParseDate($dateString);
322    
323  Traces error messages and call stacks.  Convert a date into a PERL time number. This method expects a date-like string
324    and parses it into a number. The string must be vaguely date-like or it will
325    return an undefined value. Our requirement is that a month and day be
326    present and that three pieces of the date string (time of day, month and day,
327    year) be separated by likely delimiters, such as spaces, commas, and such-like.
328    
329  =back  If a time of day is present, it must be in military time with two digits for
330    everything but the hour.
331    
332  C<SQL> is only turned on if the C<-sql> option is specified in the command line.  The year must be exactly four digits.
 The trace level is specified using the C<-trace> command-line option. For example,  
 the following command line for C<TransactFeatures> turns on SQL tracing and runs  
 all tracing at level 3.  
333    
334      TransactFeatures -trace=3 -sql register ../xacts IDs.tbl  Additional stuff can be in the string. We presume it's time zones or weekdays or something
335    equally innocuous. This means, however, that a sufficiently long sentence with date-like
336    parts in it may be interpreted as a date. Hopefully this will not be a problem.
337    
338  Standard tracing is output to the standard output and echoed to the file  It should be guaranteed that this method will parse the output of the L</Now> function.
 C<trace>I<$$>C<.log> in the FIG temporary directory, where I<$$> is the  
 process ID. You can also specify the C<user> parameter to put a user ID  
 instead of a process ID in the trace file name. So, for example  
339    
340  The default trace level is 2. To get all messages, specify a trace level of 4.  The parameters are as follows.
 For a genome-by-genome update, use 3.  
341    
342      TransactFeatures -trace=3 -sql -user=Bruce register ../xacts IDs.tbl  =over 4
343    
344  would send the trace output to C<traceBruce.log> in the temporary directory.  =item dateString
345    
346  The I<options> parameter is a reference to a hash containing the command-line  The date string to convert.
 options, their default values, and an explanation of what they mean. Command-line  
 options may be in the form of switches or keywords. In the case of a switch, the  
 option value is 1 if it is specified and 0 if it is not specified. In the case  
 of a keyword, the value is separated from the option name by an equal sign. You  
 can see this last in the command-line example above.  
347    
348  You can specify a different default trace level by setting C<$options->{trace}>  =item RETURN
 prior to calling this method.  
349    
350  An example at this point would help. Consider, for example, the command-line utility  Returns a PERL time, that is, a number of seconds since the epoch, or C<undef> if
351  C<TransactFeatures>. It accepts a list of positional parameters plus the options  the date string is invalid. A valid date string must contain a month and day.
 C<safe>, C<noAlias>, C<start>, and C<tblFiles>. To start up this command, we execute  
 the following code.  
352    
353      my ($options, @parameters) = Tracer::StandardSetup(["DocUtils"],  =back
                         { safe => [0, "use database transactions"],  
                           noAlias => [0, "do not expect aliases in CHANGE transactions"],  
                           start => [' ', "start with this genome"],  
                           tblFiles => [0, "output TBL files containing the corrected IDs"] },  
                         "command transactionDirectory IDfile",  
                       @ARGV);  
354    
355    =cut
356    
357  The call to C<ParseCommand> specifies the default values for the options and  # Universal month conversion table.
358  stores the actual options in a hash that is returned as C<$options>. The  use constant MONTHS => {    Jan =>  0, January   =>  0, '01' =>  0,  '1' =>  0,
359  positional parameters are returned in C<@parameters>.                              Feb =>  1, February  =>  1, '02' =>  1,  '2' =>  1,
360                                Mar =>  2, March     =>  2, '03' =>  2,  '3' =>  2,
361                                Apr =>  3, April     =>  3, '04' =>  3,  '4' =>  3,
362                                May =>  4, May       =>  4, '05' =>  4,  '5' =>  4,
363                                Jun =>  5, June      =>  5, '06' =>  5,  '6' =>  5,
364                                Jul =>  6, July      =>  6, '07' =>  6,  '7' =>  6,
365                                Aug =>  7, August    =>  7, '08' =>  7,  '8' =>  7,
366                                Sep =>  8, September =>  8, '09' =>  8,  '9' =>  8,
367                                Oct =>  9, October  =>   9, '10' =>  9,
368                                Nov => 10, November =>  10, '11' => 10,
369                                Dec => 11, December =>  11, '12' => 11
370                            };
371    
372  The following is a sample command line for C<TransactFeatures>.  sub ParseDate {
373        # Get the parameters.
374        my ($dateString) = @_;
375        # Declare the return variable.
376        my $retVal;
377        # Find the month and day of month. There are two ways that can happen. We check for the
378        # numeric style first. That way, if the user's done something like "Sun 12/22", then we
379        # won't be fooled into thinking the month is Sunday.
380        if ($dateString =~ m#\b(\d{1,2})/(\d{1,2})\b# || $dateString =~ m#\b(\w+)\s(\d{1,2})\b#) {
381            my ($mon, $mday) = (MONTHS->{$1}, $2);
382            # Insist that the month and day are valid.
383            if (defined($mon) && $2 >= 1 && $2 <= 31) {
384                # Find the time.
385                my ($hour, $min, $sec) = (0, 0, 0);
386                if ($dateString =~ /\b(\d{1,2}):(\d{2}):(\d{2})\b/) {
387                    ($hour, $min, $sec) = ($1, $2, $3);
388                }
389                # Find the year.
390                my $year;
391                if ($dateString =~ /\b(\d{4})\b/) {
392                    $year = $1;
393                } else {
394                    # Get the default year, which is this one. Note we must convert it to
395                    # the four-digit value expected by "timelocal".
396                    (undef, undef, undef, undef, undef, $year) = localtime();
397                    $year += 1900;
398                }
399                $retVal = timelocal($sec, $min, $hour, $mday, $mon, $year);
400            }
401        }
402        # Return the result.
403        return $retVal;
404    }
405    
406      TransactFeatures -trace=2 -noAlias register ../xacts IDs.tbl  =head3 LogErrors
407    
408  In this case, C<register>, C<../xacts>, and C<IDs.tbl> are the positional      Tracer::LogErrors($fileName);
 parameters, and would find themselves in I<@parameters> after executing the  
 above code fragment. The tracing would be set to level 2, and the categories  
 would be C<Tracer>, and <DocUtils>. C<Tracer> is standard,  
 and C<DocUtils> was included because it came in within the first parameter  
 to this method. The I<$options> hash would be  
409    
410      { trace => 2, sql => 0, safe => 0,  Route the standard error output to a log file.
       noAlias => 1, start => ' ', tblFiles => 0 }  
411    
412  Use of C<StandardSetup> in this way provides a simple way of performing  =over 4
 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.  
413    
414  If the C<background> option is specified on the command line, then the  =item fileName
 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  
415    
416      -user=Bruce -background  Name of the file to receive the error output.
417    
418  then the trace output would go to C<traceBruce.log>, the standard output to  =back
 C<outBruce.log>, and the error output to C<errBruce.log>. This is designed to  
 simplify starting a command in the background.  
419    
420  Finally, if the special option C<-h> is specified, the option names will  =cut
 be traced at level 0 and the program will exit without processing.  
 This provides a limited help capability. For example, if the user enters  
421    
422      TransactFeatures -h  sub LogErrors {
423        # Get the file name.
424        my ($fileName) = @_;
425        # Open the file as the standard error output.
426        open STDERR, '>', $fileName;
427    }
428    
429  he would see the following output.  =head3 Trace
430    
431      TransactFeatures [options] command transactionDirectory IDfile      Trace($message);
         -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  
432    
433  The caller has the option of modifying the tracing scheme by placing a value  Write a trace message to the target location specified in L</TSetup>. If there has not been
434  for C<trace> in the incoming options hash. The default value can be overridden,  any prior call to B<TSetup>.
 or the tracing to the standard output can be turned off by suffixing a minus  
 sign to the trace level. So, for example,  
435    
436      { trace => [0, "tracing level (default 0)"],  =over 4
        ...  
437    
438  would set the default trace level to 0 instead of 2, while  =item message
439    
440      { trace => ["2-", "tracing level (default 2)"],  Message to write.
        ...  
441    
442  would leave the default at 2, but trace only to the log file, not to the  =back
 standard output.  
443    
444  The parameters to this method are as follows.  =cut
445    
446  =over 4  sub Trace {
447        # Get the parameters.
448        my ($message) = @_;
449        # Strip off any line terminators at the end of the message. We will add
450        # new-line stuff ourselves.
451        my $stripped = Strip($message);
452        # Compute the caller information.
453        my ($callPackage, $callFile, $callLine) = caller();
454        my $callFileTitle = basename($callFile);
455        # Check the caller.
456        if ($callFileTitle ne "Tracer\.pm") {
457            # The caller isn't us, so add the caller info to the message.
458            $stripped = "[$callFileTitle $callLine] $stripped";
459        }
460        # Get the timestamp.
461        my $timeStamp = Now();
462        # Build the prefix.
463        my $level = $LevelNames[$LastLevel] || "($LastLevel)";
464        my $prefix = "[$timeStamp] [$level] ";
465        # Format the message.
466        my $formatted = "$prefix $stripped";
467        # Process according to the destination.
468        if ($Destination eq "TEXT") {
469            # Write the message to the standard output.
470            print "$formatted\n";
471        } elsif ($Destination eq "ERROR") {
472            # Write the message to the error output. Here, we want our prefix fields.
473            print STDERR "$formatted\n";
474        } elsif ($Destination eq "WARN") {
475            # Emit the message to the standard error output. It is presumed that the
476            # error logger will add its own prefix fields
477            print STDERR "$stripped\n";
478        } elsif ($Destination eq "QUEUE") {
479            # Push the message into the queue.
480            push @Queue, "$formatted";
481        } elsif ($Destination eq "HTML") {
482            # Convert the message to HTML and write it to the standard output.
483            my $escapedMessage = CGI::escapeHTML($stripped);
484            print "<p>$timeStamp $LastCategory $LastLevel: $escapedMessage</p>\n";
485        } elsif ($Destination =~ m/^>>/) {
486            # Write the trace message to an output file.
487            open(TRACING, $Destination) || die "Tracing open for \"$Destination\" failed: $!";
488            print TRACING "$formatted\n";
489            close TRACING;
490            # If the Tee flag is on, echo it to the standard output.
491            if ($TeeFlag) {
492                print "$formatted\n";
493            }
494        }
495    }
496    
497  =item categories  =head3 T
498    
499  Reference to a list of tracing category names. These should be names of      my $switch = T($category, $traceLevel);
 packages whose internal workings will need to be debugged to get the  
 command working.  
500    
501  =item options      or
502    
503  Reference to a hash containing the legal options for the current command mapped      my $switch = T($traceLevel);
 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).  
504    
505  =item parmHelp  Return TRUE if the trace level is at or above a specified value and the specified category
506    is active, else FALSE. If no category is specified, the caller's package name is used.
507    
508  A string that vaguely describes the positional parameters. This is used  =over 4
 if the user specifies the C<-h> option.  
509    
510  =item argv  =item category
511    
512  List of command line parameters, including the option switches, which must  Category to which the message belongs. If not specified, the caller's package name is
513  precede the positional parameters and be prefixed by a hyphen.  used.
514    
515    =item traceLevel
516    
517    Relevant tracing level.
518    
519  =item RETURN  =item RETURN
520    
521  Returns a list. The first element of the list is the reference to a hash that  TRUE if a message at the specified trace level would appear in the trace, else FALSE.
 maps the command-line option switches to their values. These will either be the  
 default values or overrides specified on the command line. The remaining  
 elements of the list are the position parameters, in order.  
522    
523  =back  =back
524    
525  =cut  =cut
526    
527  sub StandardSetup {  sub T {
528        # Declare the return variable.
529        my $retVal = 0;
530        # Only proceed if tracing is turned on.
531        if ($Destination ne "NONE") {
532      # Get the parameters.      # Get the parameters.
533      my ($categories, $options, $parmHelp, @argv) = @_;          my ($category, $traceLevel) = @_;
534      # Add the tracing options.          if (!defined $traceLevel) {
535      if (! exists $options->{trace}) {              # Here we have no category, so we need to get the calling package.
536          $options->{trace} = [2, "tracing level"];              # The calling package is normally the first parameter. If it is
537      }              # omitted, the first parameter will be the tracelevel. So, the
538      $options->{sql} = [0, "turn on SQL tracing"];              # first thing we do is shift the so-called category into the
539      $options->{h} = [0, "display command-line options"];              # $traceLevel variable where it belongs.
540      $options->{user} = [$$, "trace log file name suffix"];              $traceLevel = $category;
541      $options->{background} = [0, "spool standard and error output"];              my ($package, $fileName, $line) = caller;
542      # Create a parsing hash from the options hash. The parsing hash              # If there is no calling package, we default to "main".
543      # contains the default values rather than the default value              if (!$package) {
544      # and the description. While we're at it, we'll memorize the                  $category = "main";
     # length of the longest option name.  
     my $longestName = 0;  
     my %parseOptions = ();  
     for my $key (keys %{$options}) {  
         if (length $key > $longestName) {  
             $longestName = length $key;  
         }  
         $parseOptions{$key} = $options->{$key}->[0];  
     }  
     # Parse the command line.  
     my ($retOptions, @retParameters) = ParseCommand(\%parseOptions, @argv);  
     # Get the logfile suffix.  
     my $suffix = $retOptions->{user};  
     # Check for background mode.  
     if ($retOptions->{background}) {  
         my $outFileName = "$FIG_Config::temp/out$suffix.log";  
         my $errFileName = "$FIG_Config::temp/err$suffix.log";  
         open STDOUT, ">$outFileName";  
         open STDERR, ">$errFileName";  
     }  
     # Now we want to set up tracing. First, we need to know if SQL is to  
     # be traced.  
     my @cats = @{$categories};  
     if ($retOptions->{sql}) {  
         push @cats, "SQL";  
     }  
     # Add the default categories.  
     push @cats, "Tracer";  
     # Next, we create the category string by joining the categories.  
     my $cats = join(" ", @cats);  
     # Check to determine whether or not the caller wants to turn off tracing  
     # to the standard output.  
     my $traceLevel = $retOptions->{trace};  
     my $textOKFlag = 1;  
     if ($traceLevel =~ /^(.)-/) {  
         $traceLevel = $1;  
         $textOKFlag = 0;  
     }  
     # 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";  
         }  
         # Close the test file.  
         close TESTTRACE;  
     } else {  
         # Here we can't trace to a file. We trace to the standard output if it's  
         # okay, and the error log otherwise.  
         if ($textOKFlag) {  
             $traceMode = "TEXT";  
545          } else {          } else {
546              $traceMode = "WARN";                  my @cats = split /::/, $package;
547          }                  $category = $cats[$#cats];
548      }      }
     # Now set up the tracing.  
     TSetup("$traceLevel $cats", $traceMode);  
     # Check for the "h" option. If it is specified, dump the command-line  
     # options and exit the program.  
     if ($retOptions->{h}) {  
         $0 =~ m#[/\\](\w+)(\.pl)?$#i;  
         print "$1 [options] $parmHelp\n";  
         for my $key (sort keys %{$options}) {  
             my $name = Pad($key, $longestName, 0, ' ');  
             my $desc = $options->{$key}->[1];  
             if ($options->{$key}->[0]) {  
                 $desc .= " (default " . $options->{$key}->[0] . ")";  
549              }              }
550              print "  $name $desc\n";          # Save the category name and level.
551            $LastCategory = $category;
552            $LastLevel = $traceLevel;
553            # Convert it to lower case before we hash it.
554            $category = lc $category;
555            # Use the category and tracelevel to compute the result.
556            if (ref $traceLevel) {
557                Confess("Bad trace level.");
558            } elsif (ref $TraceLevel) {
559                Confess("Bad trace config.");
560          }          }
561          exit(0);          $retVal = ($traceLevel <= $TraceLevel && ($AllTrace || exists $Categories{$category}));
562      }      }
563      # Return the parsed parameters.      # Return the computed result.
564      return ($retOptions, @retParameters);      return $retVal;
565  }  }
566    
567  =head3 Setups  =head3 QTrace
568    
569  C<< my $count = Tracer::Setups(); >>      my $data = QTrace($format);
570    
571  Return the number of times L</TSetup> has been called.  Return the queued trace data in the specified format.
572    
573  This method allows for the creation of conditional tracing setups where, for example, we  =over 4
574  may want to set up tracing if nobody else has done it before us.  
575    =item format
576    
577    C<html> to format the data as an HTML list, C<text> to format it as straight text.
578    
579    =back
580    
581  =cut  =cut
582    
583  sub Setups {  sub QTrace {
584      return $SetupCount;      # Get the parameter.
585        my ($format) = @_;
586        # Create the return variable.
587        my $retVal = "";
588        # Only proceed if there is an actual queue.
589        if (@Queue) {
590            # Process according to the format.
591            if ($format =~ m/^HTML$/i) {
592                # Convert the queue into an HTML list.
593                $retVal = "<ul>\n";
594                for my $line (@Queue) {
595                    my $escapedLine = CGI::escapeHTML($line);
596                    $retVal .= "<li>$escapedLine</li>\n";
597                }
598                $retVal .= "</ul>\n";
599            } elsif ($format =~ m/^TEXT$/i) {
600                # Convert the queue into a list of text lines.
601                $retVal = join("\n", @Queue) . "\n";
602            }
603            # Clear the queue.
604            @Queue = ();
605        }
606        # Return the formatted list.
607        return $retVal;
608  }  }
609    
610  =head3 Open  =head3 Confess
611    
612  C<< my $handle = Open($fileHandle, $fileSpec, $message); >>      Confess($message);
613    
614  Open a file.  Trace the call stack and abort the program with the specified message. When used with
615    the OR operator and the L</Assert> method, B<Confess> can function as a debugging assert.
616    So, for example
617    
618  The I<$fileSpec> is essentially the second argument of the PERL C<open>      Assert($recNum >= 0) || Confess("Invalid record number $recNum.");
 function. The mode is specified using Unix-like shell information. So, for  
 example,  
619    
620      Open(\*LOGFILE, '>>/usr/spool/news/twitlog', "Could not open twit log.");  Will abort the program with a stack trace if the value of C<$recNum> is negative.
621    
622  would open for output appended to the specified file, and  =over 4
623    
624      Open(\*DATASTREAM, "| sort -u >$outputFile", "Could not open $outputFile.");  =item message
625    
626  would open a pipe that sorts the records written and removes duplicates. Note  Message to include in the trace.
 the use of file handle syntax in the Open call. To use anonymous file handles,  
 code as follows.  
627    
628      my $logFile = Open(undef, '>>/usr/spool/news/twitlog', "Could not open twit log.");  =back
629    
630  The I<$message> parameter is used if the open fails. If it is set to C<0>, then  =cut
 the open returns TRUE if successful and FALSE if an error occurred. Otherwise, a  
 failed open will throw an exception and the third parameter will be used to construct  
 an error message. If the parameter is omitted, a standard message is constructed  
 using the file spec.  
631    
632      Could not open "/usr/spool/news/twitlog"  sub Confess {
633        # Get the parameters.
634        my ($message) = @_;
635        # Set up the category and level.
636        $LastCategory = "(confess)";
637        $LastLevel = 0;
638        if (! defined($FIG_Config::no_tool_hdr)) {
639            # Here we have a tool header. Display its length so that the user can adjust the line numbers.
640            my $toolHeaderFile = "$FIG_Config::fig_disk/dist/releases/current/$FIG_Config::arch/tool_hdr";
641            # Only proceed if the tool header file is actually present.
642            if (-f $toolHeaderFile) {
643                my $fh;
644                if (open $fh, "<$toolHeaderFile") {
645                    my @lines = <$fh>;
646                    Trace("Tool header has " . scalar(@lines) . " lines.");
647                }
648            }
649        }
650        # Trace the call stack.
651        Cluck($message);
652        # Abort the program.
653        croak(">>> $message");
654    }
655    
656  Note that the mode characters are automatically cleaned from the file name.  =head3 Assert
 The actual error message from the file system will be captured and appended to the  
 message in any case.  
657    
658      Could not open "/usr/spool/news/twitlog": file not found.      Assert($condition1, $condition2, ... $conditionN);
659    
660  In some versions of PERL the only error message we get is a number, which  Return TRUE if all the conditions are true. This method can be used in conjunction with
661  corresponds to the C++ C<errno> value.  the OR operator and the L</Confess> method as a debugging assert.
662    So, for example
663    
664      Could not open "/usr/spool/news/twitlog": 6.      Assert($recNum >= 0) || Confess("Invalid record number $recNum.");
665    
666  =over 4  Will abort the program with a stack trace if the value of C<$recNum> is negative.
667    
668  =item fileHandle  =cut
669    sub Assert {
670        my $retVal = 1;
671        LOOP: for my $condition (@_) {
672            if (! $condition) {
673                $retVal = 0;
674                last LOOP;
675            }
676        }
677        return $retVal;
678    }
679    
680  File handle. If this parameter is C<undef>, a file handle will be generated  =head3 Cluck
 and returned as the value of this method.  
681    
682  =item fileSpec      Cluck($message);
683    
684  File name and mode, as per the PERL C<open> function.  Trace the call stack. Note that for best results, you should qualify the call with a
685    trace condition. For example,
686    
687  =item message (optional)      Cluck("Starting record parse.") if T(3);
688    
689  Error message to use if the open fails. If omitted, a standard error message  will only trace the stack if the trace level for the package is 3 or more.
 will be generated. In either case, the error information from the file system  
 is appended to the message. To specify a conditional open that does not throw  
 an error if it fails, use C<0>.  
690    
691  =item RETURN  =over 4
692    
693  Returns the name of the file handle assigned to the file, or C<undef> if the  =item message
694  open failed.  
695    Message to include in the trace.
696    
697  =back  =back
698    
699  =cut  =cut
700    
701  sub Open {  sub Cluck {
702      # Get the parameters.      # Get the parameters.
703      my ($fileHandle, $fileSpec, $message) = @_;      my ($message) = @_;
704      # Attempt to open the file.      # Trace what's happening.
705      my $rv = open $fileHandle, $fileSpec;      Trace("Stack trace for event: $message");
706      # If the open failed, generate an error message.      my $confession = longmess($message);
707      if (! $rv) {      # Convert the confession to a series of trace messages.
708          # Save the system error message.      for my $line (split /\s*\n/, $confession) {
709          my $sysMessage = $!;          # Only proceed if this call trace is for a method outside Tracer itself.
710          # See if we need a default message.          if ($line !~ /Tracer\.pm/) {
711          if (!$message) {              # Replace the leading tab with a series of spaces.
712              # Clean any obvious mode characters and leading spaces from the              $line =~ s/\t/    /;
713              # filename.              # Trace the line.
714              my ($fileName) = FindNamePart($fileSpec);              Trace($line);
             $message = "Could not open \"$fileName\"";  
715          }          }
         # Terminate with an error using the supplied message and the  
         # error message from the file system.  
         Confess("$message: $!");  
716      }      }
     # Return the file handle.  
     return $fileHandle;  
717  }  }
718    
719  =head3 FindNamePart  =head3 ScriptSetup (deprecated)
720    
721  C<< my ($fileName, $start, $len) = Tracer::FindNamePart($fileSpec); >>      my ($cgi, $varHash) = ScriptSetup($noTrace);
722    
723  Extract the portion of a file specification that contains the file name.  Perform standard tracing and debugging setup for scripts. The value returned is
724    the CGI object followed by a pre-built variable hash. At the end of the script,
725    the client should call L</ScriptFinish> to output the web page.
726    
727  A file specification is the string passed to an C<open> call. It specifies the file  This method calls L</ETracing> to configure tracing, which allows the tracing
728  mode and name. In a truly complex situation, it can specify a pipe sequence. This  to be configured via the emergency tracing form on the debugging control panel.
729  method assumes that the file name is whatever follows the first angle bracket  Tracing will then be turned on automatically for all programs that use the L</ETracing>
730  sequence.  So, for example, in the following strings the file name is  method, which includes every program that uses this method or L</StandardSetup>.
 C</usr/fig/myfile.txt>.  
   
     >>/usr/fig/myfile.txt  
     </usr/fig/myfile.txt  
     | sort -u > /usr/fig/myfile.txt  
   
 If the method cannot find a file name using its normal methods, it will return the  
 whole incoming string.  
731    
732  =over 4  =over 4
733    
734  =item fileSpec  =item noTrace (optional)
735    
736  File specification string from which the file name is to be extracted.  If specified, tracing will be suppressed. This is useful if the script wants to set up
737    tracing manually.
738    
739  =item RETURN  =item RETURN
740    
741  Returns a three-element list. The first element contains the file name portion of  Returns a two-element list consisting of a CGI query object and a variable hash for
742  the specified string, or the whole string if a file name cannot be found via normal  the output page.
 methods. The second element contains the start position of the file name portion and  
 the third element contains the length.  
743    
744  =back  =back
745    
746  =cut  =cut
747  #: Return Type $;  
748  sub FindNamePart {  sub ScriptSetup {
749      # Get the parameters.      # Get the parameters.
750      my ($fileSpec) = @_;      my ($noTrace) = @_;
751      # Default to the whole input string.      # Get the CGI query object.
752      my ($retVal, $pos, $len) = ($fileSpec, 0, length $fileSpec);      my $cgi = CGI->new();
753      # Parse out the file name if we can.      # Set up tracing if it's not suppressed.
754      if ($fileSpec =~ m/(<|>>?)(.+?)(\s*)$/) {      ETracing($cgi) unless $noTrace;
755          $retVal = $2;      # Create the variable hash.
756          $len = length $retVal;      my $varHash = { results => '' };
757          $pos = (length $fileSpec) - (length $3) - $len;      # Return the query object and variable hash.
758      }      return ($cgi, $varHash);
     # Return the result.  
     return ($retVal, $pos, $len);  
759  }  }
760    
761  =head3 OpenDir  =head3 ETracing
   
 C<< my @files = OpenDir($dirName, $filtered, $flag); >>  
   
 Open a directory and return all the file names. This function essentially performs  
 the functions of an C<opendir> and C<readdir>. If the I<$filtered> parameter is  
 set to TRUE, all filenames beginning with a period (C<.>), dollar sign (C<$>),  
 or pound sign (C<#>) and all filenames ending with a tilde C<~>) will be  
 filtered out of the return list. If the directory does not open and I<$flag> is not  
 set, an exception is thrown. So, for example,  
   
     my @files = OpenDir("/Volumes/fig/contigs", 1);  
   
 is effectively the same as  
   
     opendir(TMP, "/Volumes/fig/contigs") || Confess("Could not open /Volumes/fig/contigs.");  
     my @files = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir(TMP);  
   
 Similarly, the following code  
762    
763      my @files = grep { $_ =~ /^\d/ } OpenDir("/Volumes/fig/orgs", 0, 1);      ETracing($parameter);
764    
765  Returns the names of all files in C</Volumes/fig/orgs> that begin with digits and  Set up emergency tracing. Emergency tracing is tracing that is turned
766  automatically returns an empty list if the directory fails to open.  on automatically for any program that calls this method. The emergency
767    tracing parameters are stored in a a file identified by a tracing key.
768    If this method is called with a CGI object, then the tracing key is
769    taken from a cookie. If it is called with no parameters, then the tracing
770    key is taken from an environment variable. If it is called with a string,
771    the tracing key is that string.
772    
773  =over 4  =over 4
774    
775  =item dirName  =item parameter
   
 Name of the directory to open.  
   
 =item filtered  
   
 TRUE if files whose names begin with a period (C<.>) should be automatically removed  
 from the list, else FALSE.  
   
 =item flag  
776    
777  TRUE if a failure to open is okay, else FALSE  A parameter from which the tracing key is computed. If it is a scalar,
778    that scalar is used as the tracing key. If it is a CGI object, the
779    tracing key is taken from the C<IP> cookie. If it is omitted, the
780    tracing key is taken from the C<TRACING> environment variable. If it
781    is a CGI object and emergency tracing is not on, the C<Trace> and
782    C<TF> parameters will be used to determine the type of tracing.
783    
784  =back  =back
785    
786  =cut  =cut
787  #: Return Type @;  
788  sub OpenDir {  sub ETracing {
789      # Get the parameters.      # Get the parameter.
790      my ($dirName, $filtered, $flag) = @_;      my ($parameter) = @_;
791      # Declare the return variable.      # Check for CGI mode.
792      my @retVal = ();      my $cgi = (ref $parameter eq 'CGI' ? $parameter : undef);
793      # Open the directory.      # Default to no tracing except errors.
794      if (opendir(my $dirHandle, $dirName)) {      my ($tracing, $dest) = ("0", "WARN");
795          # The directory opened successfully. Get the appropriate list according to the      # Check for emergency tracing.
796          # strictures of the filter parameter.      my $tkey = EmergencyKey($parameter);
797          if ($filtered) {      my $emergencyFile = EmergencyFileName($tkey);
798              @retVal = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir $dirHandle;      if (-e $emergencyFile) {
799            # We have the file. Read in the data.
800            my @tracing = GetFile($emergencyFile);
801            # Pull off the time limit.
802            my $expire = shift @tracing;
803            # Convert it to seconds.
804            $expire *= 3600;
805            # Check the file data.
806            my $stat = stat($emergencyFile);
807            my ($now) = gettimeofday;
808            if ($now - $stat->mtime > $expire) {
809                # Delete the expired file.
810                unlink $emergencyFile;
811          } else {          } else {
812              @retVal = readdir $dirHandle;              # Emergency tracing is on. Pull off the destination and
813                # the trace level;
814                $dest = shift @tracing;
815                my $level = shift @tracing;
816                # Convert the destination to a real tracing destination.
817                # temp directory.
818                $dest = EmergencyTracingDest($tkey, $dest);
819                # Insure Tracer is specified.
820                my %moduleHash = map { $_ => 1 } @tracing;
821                $moduleHash{Tracer} = 1;
822                # Set the trace parameter.
823                $tracing = join(" ", $level, sort keys %moduleHash);
824            }
825        } elsif (defined $cgi) {
826            # There's no emergency tracing, but we have a CGI object, so check
827            # for tracing from the form parameters.
828            if ($cgi->param('Trace')) {
829                # Here the user has requested tracing via a form.
830                $dest = ($cgi->param('TF') ? ">$FIG_Config::temp/Trace$$.log" : "QUEUE");
831                $tracing = $cgi->param('Trace') . " Tracer";
832            }
833        }
834        # Setup the tracing we've determined from all the stuff above.
835        TSetup($tracing, $dest);
836        # Check to see if we're a web script.
837        if (defined $cgi) {
838            # Yes we are. Trace the form and environment data.
839            TraceParms($cgi);
840            # Check for RAW mode. In raw mode, we print a fake header so that we see everything
841            # emitted by the script in its raw form.
842            if (T(Raw => 3)) {
843                print CGI::header(-type => 'text/plain', -tracing => 'Raw');
844          }          }
     } elsif (! $flag) {  
         # Here the directory would not open and it's considered an error.  
         Confess("Could not open directory $dirName.");  
845      }      }
     # Return the result.  
     return @retVal;  
846  }  }
847    
848  =head3 SetLevel  =head3 EmergencyFileName
849    
850  C<< Tracer::SetLevel($newLevel); >>      my $fileName = Tracer::EmergencyFileName($tkey);
851    
852  Modify the trace level. A higher trace level will cause more messages to appear.  Return the emergency tracing file name. This is the file that specifies
853    the tracing information.
854    
855  =over 4  =over 4
856    
857  =item newLevel  =item tkey
   
 Proposed new trace level.  
   
 =back  
   
 =cut  
858    
859  sub SetLevel {  Tracing key for the current program.
     $TraceLevel = $_[0];  
 }  
860    
861  =head3 Now  =item RETURN
862    
863  C<< my $string = Tracer::Now(); >>  Returns the name of the file to contain the emergency tracing information.
864    
865  Return a displayable time stamp containing the local time.  =back
866    
867  =cut  =cut
868    
869  sub Now {  sub EmergencyFileName {
870      my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);      # Get the parameters.
871      my $retVal = _p2($mon+1) . "/" . _p2($mday) . "/" . ($year + 1900) . " " .      my ($tkey) = @_;
872                   _p2($hour) . ":" . _p2($min) . ":" . _p2($sec);      # Compute the emergency tracing file name.
873      return $retVal;      return "$FIG_Config::temp/Emergency$tkey.txt";
 }  
   
 # Pad a number to 2 digits.  
 sub _p2 {  
     my ($value) = @_;  
     $value = "0$value" if ($value < 10);  
     return $value;  
874  }  }
875    
876  =head3 LogErrors  =head3 EmergencyFileTarget
877    
878  C<< Tracer::LogErrors($fileName); >>      my $fileName = Tracer::EmergencyFileTarget($tkey);
879    
880  Route the standard error output to a log file.  Return the emergency tracing target file name. This is the file that receives
881    the tracing output for file-based tracing.
882    
883  =over 4  =over 4
884    
885  =item fileName  =item tkey
886    
887  Name of the file to receive the error output.  Tracing key for the current program.
888    
889    =item RETURN
890    
891    Returns the name of the file to contain the trace output.
892    
893  =back  =back
894    
895  =cut  =cut
896    
897  sub LogErrors {  sub EmergencyFileTarget {
898      # Get the file name.      # Get the parameters.
899      my ($fileName) = @_;      my ($tkey) = @_;
900      # Open the file as the standard error output.      # Compute the emergency tracing file name.
901      open STDERR, '>', $fileName;      return "$FIG_Config::temp/trace$tkey.log";
902  }  }
903    
904  =head3 ReadOptions  =head3 EmergencyTracingDest
905    
906  C<< my %options = Tracer::ReadOptions($fileName); >>      my $dest = Tracer::EmergencyTracingDest($tkey, $myDest);
907    
908  Read a set of options from a file. Each option is encoded in a line of text that has the  This method converts an emergency tracing destination to a real
909  format  tracing destination. The main difference is that if the
910    destination is C<FILE> or C<APPEND>, we convert it to file
911    output. If the destination is C<DUAL>, we convert it to file
912    and standard output.
913    
914  I<optionName>C<=>I<optionValue>C<; >I<comment>  =over 4
915    
916  The option name must consist entirely of letters, digits, and the punctuation characters  =item tkey
 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.  
917    
918  =over 4  Tracing key for this environment.
919    
920  =item fileName  =item myDest
921    
922  Name of the file containing the option data.  Destination from the emergency tracing file.
923    
924  =item RETURN  =item RETURN
925    
926  Returns a hash mapping the option names specified in the file to their corresponding option  Returns a destination that can be passed into L</TSetup>.
 value.  
927    
928  =back  =back
929    
930  =cut  =cut
931    
932  sub ReadOptions {  sub EmergencyTracingDest {
933      # Get the parameters.      # Get the parameters.
934      my ($fileName) = @_;      my ($tkey, $myDest) = @_;
935      # Open the file.      # Declare the return variable.
936      (open CONFIGFILE, "<$fileName") || Confess("Could not open option file $fileName.");      my $retVal = $myDest;
937      # Count the number of records read.      # Process according to the destination value.
938      my ($records, $comments) = 0;      if ($myDest eq 'FILE') {
939      # Create the return hash.          $retVal = ">" . EmergencyFileTarget($tkey);
940      my %retVal = ();      } elsif ($myDest eq 'APPEND') {
941      # Loop through the file, accumulating key-value pairs.          $retVal = ">>" . EmergencyFileTarget($tkey);
942      while (my $line = <CONFIGFILE>) {      } elsif ($myDest eq 'DUAL') {
943          # Denote we've read a line.          $retVal = "+>" . EmergencyFileTarget($tkey);
944          $records++;      } elsif ($myDest eq 'WARN') {
945          # Determine the line type.          $retVal = "WARN";
         if ($line =~ /^\s*[\n\r]/) {  
             # A blank line is a comment.  
             $comments++;  
         } elsif ($line =~ /^\s*([A-Za-z0-9_\.]+)=([^;]*);/) {  
             # Here we have an option assignment.  
             retVal{$1} = $2;  
         } elsif ($line =~ /^\s*;/) {  
             # Here we have a text comment.  
             $comments++;  
         } else {  
             # Here we have an invalid line.  
             Trace("Invalid option statement in record $records.") if T(0);  
         }  
946      }      }
947      # Return the hash created.      # Return the result.
948      return %retVal;      return $retVal;
949  }  }
950    
951  =head3 GetOptions  =head3 Emergency
952    
953  C<< Tracer::GetOptions(\%defaults, \%options); >>      Emergency($key, $hours, $dest, $level, @modules);
954    
955  Merge a specified set of options into a table of defaults. This method takes two hash references  Turn on emergency tracing. This method is normally invoked over the web from
956  as input and uses the data from the second to update the first. If the second does not exist,  a debugging console, but it can also be called by the C<trace.pl> script.
957  there will be no effect. An error will be thrown if one of the entries in the second hash does not  The caller specifies the duration of the emergency in hours, the desired tracing
958  exist in the first.  destination, the trace level, and a list of the trace modules to activate.
959    For the length of the duration, when a program in an environment with the
960    specified tracing key active invokes a Sprout CGI script, tracing will be
961    turned on automatically. See L</TSetup> for more about tracing setup and
962    L</ETracing> for more about emergency tracing.
963    
964  Consider the following example.  =over 4
965    
966  C<< my $optionTable = GetOptions({ dbType => 'mySQL', trace => 0 }, $options); >>  =item tkey
967    
968  In this example, the variable B<$options> is expected to contain at most two options-- B<dbType> and  The tracing key. This is used to identify the control file and the trace file.
 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  
969    
970  C<< {databaseType => 'Oracle'} >>  =item hours
971    
972  an error will occur because the B<databaseType> option does not exist.  Number of hours to keep emergency tracing alive.
973    
974  =over 4  =item dest
975    
976  =item defaults  Tracing destination. If no path information is specified for a file
977    destination, it is put in the FIG temporary directory.
978    
979  Table of default option values.  =item level
980    
981  =item options  Tracing level. A higher level means more trace messages.
982    
983  Table of overrides, if any.  =item modules
984    
985    A list of the tracing modules to activate.
986    
987    =back
988    
989    =cut
990    
991    sub Emergency {
992        # Get the parameters.
993        my ($tkey, $hours, $dest, $level, @modules) = @_;
994        # Create the emergency file.
995        my $specFile = EmergencyFileName($tkey);
996        my $outHandle = Open(undef, ">$specFile");
997        print $outHandle join("\n", $hours, $dest, $level, @modules, "");
998    }
999    
1000    =head3 EmergencyKey
1001    
1002        my $tkey = EmergencyKey($parameter);
1003    
1004    Return the Key to be used for emergency tracing. This could be an IP address,
1005     a session ID, or a user name, depending on the environment.
1006    
1007    =over 4
1008    
1009    =item parameter
1010    
1011    Parameter defining the method for finding the tracing key. If it is a scalar,
1012    then it is presumed to be the tracing key itself. If it is a CGI object, then
1013    the tracing key is taken from the C<IP> cookie. Otherwise, the tracing key is
1014    taken from the C<TRACING> environment variable.
1015    
1016  =item RETURN  =item RETURN
1017    
1018  Returns a reference to the default table passed in as the first parameter.  Returns the key to be used for labels in emergency tracing.
1019    
1020  =back  =back
1021    
1022  =cut  =cut
1023    
1024  sub GetOptions {  sub EmergencyKey {
1025      # Get the parameters.      # Get the parameters.
1026      my ($defaults, $options) = @_;      my ($parameter) = @_;
1027      # Check for overrides.      # Declare the return variable.
1028      if ($options) {      my $retVal;
1029          # Loop through the overrides.      # Determine the parameter type.
1030          while (my ($option, $setting) = each %{$options}) {      if (! defined $parameter) {
1031              # Insure this override exists.          # Here we're supposed to check the environment.
1032              if (!exists $defaults->{$option}) {          $retVal = $ENV{TRACING};
1033                  croak "Unrecognized option $option encountered.";      } else {
1034              } else {          my $ptype = ref $parameter;
1035                  # Apply the override.          if ($ptype eq 'CGI') {
1036                  $defaults->{$option} = $setting;              # Here we were invoked from a web page. Look for a cookie.
1037              }              $retVal = $parameter->cookie('IP');
1038          }          } elsif (! $ptype) {
1039                # Here the key was passed in.
1040                $retVal = $parameter;
1041            }
1042        }
1043        # If no luck finding a key, use the PID.
1044        if (! defined $retVal) {
1045            $retVal = $$;
1046      }      }
1047      # Return the merged table.      # Return the result.
1048      return $defaults;      return $retVal;
1049  }  }
1050    
 =head3 MergeOptions  
   
 C<< Tracer::MergeOptions(\%table, \%defaults); >>  
1051    
1052  Merge default values into a hash table. This method looks at the key-value pairs in the  =head3 TraceParms
 second (default) hash, and if a matching key is not found in the first hash, the default  
 pair is copied in. The process is similar to L</GetOptions>, but there is no error-  
 checking and no return value.  
1053    
1054  =over 4      Tracer::TraceParms($cgi);
1055    
1056  =item table  Trace the CGI parameters at trace level CGI => 3 and the environment variables
1057    at level CGI => 4. A self-referencing URL is traced at level CGI => 2.
1058    
1059  Hash table to be updated with the default values.  =over 4
1060    
1061  =item defaults  =item cgi
1062    
1063  Default values to be merged into the first hash table if they are not already present.  CGI query object containing the parameters to trace.
1064    
1065  =back  =back
1066    
1067  =cut  =cut
1068    
1069  sub MergeOptions {  sub TraceParms {
1070      # Get the parameters.      # Get the parameters.
1071      my ($table, $defaults) = @_;      my ($cgi) = @_;
1072      # Loop through the defaults.      if (T(CGI => 2)) {
1073      while (my ($key, $value) = each %{$defaults}) {          # Here we trace the GET-style URL for the script.
1074          if (!exists $table->{$key}) {          Trace("[URL] " . $cgi->url(-relative => 1, -query => 1));
1075              $table->{$key} = $value;      }
1076        if (T(CGI => 3)) {
1077            # Here we want to trace the parameter data.
1078            my @names = $cgi->param;
1079            for my $parmName (sort @names) {
1080                # Note we skip the Trace parameters, which are for our use only.
1081                if ($parmName ne 'Trace' && $parmName ne 'TF') {
1082                    my @values = $cgi->param($parmName);
1083                    Trace("[CGI] $parmName = " . join(", ", @values));
1084                }
1085            }
1086            # Display the request method.
1087            my $method = $cgi->request_method();
1088            Trace("Method: $method");
1089        }
1090        if (T(CGI => 4)) {
1091            # Here we want the environment data too.
1092            for my $envName (sort keys %ENV) {
1093                Trace("[ENV] $envName = $ENV{$envName}");
1094          }          }
1095      }      }
1096  }  }
1097    
1098  =head3 Trace  =head3 TraceImages
1099    
1100  C<< Trace($message); >>      Tracer::TraceImages($htmlString);
1101    
1102  Write a trace message to the target location specified in L</TSetup>. If there has not been  Trace information about all of an html document's images. The tracing
1103  any prior call to B<TSetup>.  will be for type "IMG" at level 3. The image's source string
1104    will be displayed. This is generally either the URL of the image or
1105    raw data for the image itself. If the source is too long, only the first 300
1106    characters will be shown at trace level 3. The entire source will be shown,
1107    however, at trace level 4. This method is not very smart, and might catch
1108    Javascript code, but it is still useful when debugging the arcane
1109    behavior of images in multiple browser environments.
1110    
1111  =over 4  =over 4
1112    
1113  =item message  =item htmlString
1114    
1115  Message to write.  HTML text for an outgoing web page.
1116    
1117  =back  =back
1118    
1119  =cut  =cut
1120    
1121  sub Trace {  sub TraceImages {
1122      # Get the parameters.      # Only proceed if we're at the proper trace level.
1123      my ($message) = @_;      if (T(IMG => 3)) {
1124      # Get the timestamp.          # For performance reasons we're manipulating $_[0] instead of retrieving the string
1125      my $timeStamp = Now();          # into a variable called "$htmlString". This is because we expect html strings to be
1126      # Format the message. Note we strip off any line terminators at the end.          # long, and don't want to copy them any more than we have to.
1127      my $formatted = "[$timeStamp] <$LastCategory>: " . Strip($message);          Trace(length($_[0]) . " characters in web page.");
1128      # Process according to the destination.          # Loop through the HTML, culling image tags.
1129      if ($Destination eq "TEXT") {          while ($_[0] =~ /<img\s+[^>]+?src="([^"]+)"/sgi) {
1130          # Write the message to the standard output.              # Extract the source string and determine whether or not it's too long.
1131          print "$formatted\n";              my $srcString = $1;
1132      } elsif ($Destination eq "ERROR") {              my $pos = pos($_[0]) - length($srcString);
1133          # Write the message to the error output.              my $excess = length($srcString) - 300;
1134          print STDERR "$formatted\n";              # We'll put the display string in here.
1135      } elsif ($Destination eq "QUEUE") {              my $srcDisplay = $srcString;
1136          # Push the message into the queue.              # If it's a data string, split it at the comma.
1137          push @Queue, "$formatted";              $srcDisplay =~ s/^(data[^,]+,)/$1\n/;
1138      } elsif ($Destination eq "HTML") {              # If there's no excess or we're at trace level 4, we're done. At level 3 with
1139          # Convert the message to HTML and write it to the standard output.              # a long string, however, we only show the first 300 characters.
1140          my $escapedMessage = CGI::escapeHTML($message);              if ($excess > 0 && ! T(IMG => 4)) {
1141          print "<p>$formatted</p>\n";                  $srcDisplay = substr($srcDisplay,0,300) . "\nplus $excess characters.";
1142      } elsif ($Destination eq "WARN") {              }
1143         # Emit the message as a warning.              # Output the trace message.
1144         warn $message;              Trace("Image tag at position $pos:\n$srcDisplay");
     } 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";  
1145          }          }
1146      }      }
1147  }  }
1148    
 =head3 T  
1149    
1150  C<< my $switch = T($category, $traceLevel); >>  =head3 ScriptFinish (deprecated)
1151    
1152      or      ScriptFinish($webData, $varHash);
1153    
1154  C<< my $switch = T($traceLevel); >>  Output a web page at the end of a script. Either the string to be output or the
1155    name of a template file can be specified. If the second parameter is omitted,
1156    it is assumed we have a string to be output; otherwise, it is assumed we have the
1157    name of a template file. The template should have the variable C<DebugData>
1158    specified in any form that invokes a standard script. If debugging mode is turned
1159    on, a form field will be put in that allows the user to enter tracing data.
1160    Trace messages will be placed immediately before the terminal C<BODY> tag in
1161    the output, formatted as a list.
1162    
1163  Return TRUE if the trace level is at or above a specified value and the specified category  A typical standard script would loook like the following.
 is active, else FALSE. If no category is specified, the caller's package name is used.  
1164    
1165  =over 4      BEGIN {
1166            # Print the HTML header.
1167            print "CONTENT-TYPE: text/html\n\n";
1168        }
1169        use Tracer;
1170        use CGI;
1171        use FIG;
1172        # ... more uses ...
1173    
1174  =item category      my ($cgi, $varHash) = ScriptSetup();
1175        eval {
1176            # ... get data from $cgi, put it in $varHash ...
1177        };
1178        if ($@) {
1179            Trace("Script Error: $@") if T(0);
1180        }
1181        ScriptFinish("Html/MyTemplate.html", $varHash);
1182    
1183  Category to which the message belongs. If not specified, the caller's package name is  The idea here is that even if the script fails, you'll see trace messages and
1184  used.  useful output.
1185    
1186  =item traceLevel  =over 4
1187    
1188  Relevant tracing level.  =item webData
1189    
1190  =item RETURN  A string containing either the full web page to be written to the output or the
1191    name of a template file from which the page is to be constructed. If the name
1192    of a template file is specified, then the second parameter must be present;
1193    otherwise, it must be absent.
1194    
1195  TRUE if a message at the specified trace level would appear in the trace, else FALSE.  =item varHash (optional)
1196    
1197    If specified, then a reference to a hash mapping variable names for a template
1198    to their values. The template file will be read into memory, and variable markers
1199    will be replaced by data in this hash reference.
1200    
1201  =back  =back
1202    
1203  =cut  =cut
1204    
1205  sub T {  sub ScriptFinish {
     # Declare the return variable.  
     my $retVal = 0;  
     # Only proceed if tracing is turned on.  
     if ($Destination ne "NONE") {  
1206          # Get the parameters.          # Get the parameters.
1207          my ($category, $traceLevel) = @_;      my ($webData, $varHash) = @_;
1208          if (!defined $traceLevel) {      # Check for a template file situation.
1209              # Here we have no category, so we need to get the calling package.      my $outputString;
1210              # The calling package is normally the first parameter. If it is      if (defined $varHash) {
1211              # omitted, the first parameter will be the tracelevel. So, the          # Here we have a template file. We need to determine the template type.
1212              # first thing we do is shift the so-called category into the          my $template;
1213              # $traceLevel variable where it belongs.          if ($FIG_Config::template_url && $webData =~ /\.php$/) {
1214              $traceLevel = $category;              $template = "$FIG_Config::template_url/$webData";
1215              my ($package, $fileName, $line) = caller;          } else {
1216              # If there is no calling package, we default to "main".              $template = "<<$webData";
1217              if (!$package) {          }
1218                  $category = "main";          $outputString = PageBuilder::Build($template, $varHash, "Html");
1219              } else {              } else {
1220                  $category = $package;          # Here the user gave us a raw string.
1221            $outputString = $webData;
1222              }              }
1223        # Check for trace messages.
1224        if ($Destination ne "NONE" && $TraceLevel > 0) {
1225            # We have trace messages, so we want to put them at the end of the body. This
1226            # is either at the end of the whole string or at the beginning of the BODY
1227            # end-tag.
1228            my $pos = length $outputString;
1229            if ($outputString =~ m#</body>#gi) {
1230                $pos = (pos $outputString) - 7;
1231          }          }
1232          # Save the category name.          # If the trace messages were queued, we unroll them. Otherwise, we display the
1233          $LastCategory = $category;          # destination.
1234          # Convert it to lower case before we hash it.          my $traceHtml;
1235          $category = lc $category;          if ($Destination eq "QUEUE") {
1236          # Use the category and tracelevel to compute the result.              $traceHtml = QTrace('Html');
1237          if (ref $traceLevel) {          } elsif ($Destination =~ /^>>(.+)$/) {
1238              Confess("Bad trace level.");              # Here the tracing output it to a file. We code it as a hyperlink so the user
1239          } elsif (ref $TraceLevel) {              # can copy the file name into the clipboard easily.
1240              Confess("Bad trace config.");              my $actualDest = $1;
1241                $traceHtml = "<p>Tracing output to $actualDest.</p>\n";
1242            } else {
1243                # Here we have one of the special destinations.
1244                $traceHtml = "<P>Tracing output type is $Destination.</p>\n";
1245          }          }
1246          $retVal = ($traceLevel <= $TraceLevel && ($AllTrace || exists $Categories{$category}));          substr $outputString, $pos, 0, $traceHtml;
1247      }      }
1248      # Return the computed result.      # Write the output string.
1249      return $retVal;      print $outputString;
1250    }
1251    
1252    =head2 Command-Line Utility Methods
1253    
1254    =head3 SendSMS
1255    
1256        my $msgID = Tracer::SendSMS($phoneNumber, $msg);
1257    
1258    Send a text message to a phone number using Clickatell. The FIG_Config file must contain the
1259    user name, password, and API ID for the relevant account in the hash reference variable
1260    I<$FIG_Config::phone>, using the keys C<user>, C<password>, and C<api_id>. For
1261    example, if the user name is C<BruceTheHumanPet>, the password is C<silly>, and the API ID
1262    is C<2561022>, then the FIG_Config file must contain
1263    
1264        $phone =  { user => 'BruceTheHumanPet',
1265                    password => 'silly',
1266                    api_id => '2561022' };
1267    
1268    The original purpose of this method was to insure Bruce would be notified immediately when the
1269    Sprout Load terminates. Care should be taken if you do not wish Bruce to be notified immediately
1270    when you call this method.
1271    
1272    The message ID will be returned if successful, and C<undef> if an error occurs.
1273    
1274    =over 4
1275    
1276    =item phoneNumber
1277    
1278    Phone number to receive the message, in international format. A United States phone number
1279    would be prefixed by "1". A British phone number would be prefixed by "44".
1280    
1281    =item msg
1282    
1283    Message to send to the specified phone.
1284    
1285    =item RETURN
1286    
1287    Returns the message ID if successful, and C<undef> if the message could not be sent.
1288    
1289    =back
1290    
1291    =cut
1292    
1293    sub SendSMS {
1294        # Get the parameters.
1295        my ($phoneNumber, $msg) = @_;
1296        # Declare the return variable. If we do not change it, C<undef> will be returned.
1297        my $retVal;
1298        # Only proceed if we have phone support.
1299        if (! defined $FIG_Config::phone) {
1300            Trace("Phone support not present in FIG_Config.") if T(1);
1301        } else {
1302            # Get the phone data.
1303            my $parms = $FIG_Config::phone;
1304            # Get the Clickatell URL.
1305            my $url = "http://api.clickatell.com/http/";
1306            # Create the user agent.
1307            my $ua = LWP::UserAgent->new;
1308            # Request a Clickatell session.
1309            my $resp = $ua->post("$url/sendmsg", { user => $parms->{user},
1310                                         password => $parms->{password},
1311                                         api_id => $parms->{api_id},
1312                                         to => $phoneNumber,
1313                                         text => $msg});
1314            # Check for an error.
1315            if (! $resp->is_success) {
1316                Trace("Alert failed.") if T(1);
1317            } else {
1318                # Get the message ID.
1319                my $rstring = $resp->content;
1320                if ($rstring =~ /^ID:\s+(.*)$/) {
1321                    $retVal = $1;
1322                } else {
1323                    Trace("Phone attempt failed with $rstring") if T(1);
1324                }
1325            }
1326        }
1327        # Return the result.
1328        return $retVal;
1329    }
1330    
1331    =head3 StandardSetup
1332    
1333        my ($options, @parameters) = StandardSetup(\@categories, \%options, $parmHelp, @ARGV);
1334    
1335    This method performs standard command-line parsing and tracing setup. The return
1336    values are a hash of the command-line options and a list of the positional
1337    parameters. Tracing is automatically set up and the command-line options are
1338    validated.
1339    
1340    This is a complex method that does a lot of grunt work. The parameters can
1341    be more easily understood, however, once they are examined individually.
1342    
1343    The I<categories> parameter is the most obtuse. It is a reference to a list of
1344    special-purpose tracing categories. Most tracing categories are PERL package
1345    names. So, for example, if you wanted to turn on tracing inside the B<Sprout>,
1346    B<ERDB>, and B<SproutLoad> packages, you would specify the categories
1347    
1348        ["Sprout", "SproutLoad", "ERDB"]
1349    
1350    This would cause trace messages in the specified three packages to appear in
1351    the output. There are two special tracing categories that are automatically
1352    handled by this method. In other words, if you used L</TSetup> you would need
1353    to include these categories manually, but if you use this method they are turned
1354    on automatically.
1355    
1356    =over 4
1357    
1358    =item SQL
1359    
1360    Traces SQL commands and activity.
1361    
1362    =item Tracer
1363    
1364    Traces error messages and call stacks.
1365    
1366    =back
1367    
1368    C<SQL> is only turned on if the C<-sql> option is specified in the command line.
1369    The trace level is specified using the C<-trace> command-line option. For example,
1370    the following command line for C<TransactFeatures> turns on SQL tracing and runs
1371    all tracing at level 3.
1372    
1373        TransactFeatures -trace=3 -sql register ../xacts IDs.tbl
1374    
1375    Standard tracing is output to the standard output and echoed to the file
1376    C<trace>I<$$>C<.log> in the FIG temporary directory, where I<$$> is the
1377    process ID. You can also specify the C<user> parameter to put a user ID
1378    instead of a process ID in the trace file name. So, for example
1379    
1380    The default trace level is 2. To get all messages, specify a trace level of 4.
1381    For a genome-by-genome update, use 3.
1382    
1383        TransactFeatures -trace=3 -sql -user=Bruce register ../xacts IDs.tbl
1384    
1385    would send the trace output to C<traceBruce.log> in the temporary directory.
1386    
1387    The I<options> parameter is a reference to a hash containing the command-line
1388    options, their default values, and an explanation of what they mean. Command-line
1389    options may be in the form of switches or keywords. In the case of a switch, the
1390    option value is 1 if it is specified and 0 if it is not specified. In the case
1391    of a keyword, the value is separated from the option name by an equal sign. You
1392    can see this last in the command-line example above.
1393    
1394    You can specify a different default trace level by setting C<$options->{trace}>
1395    prior to calling this method.
1396    
1397    An example at this point would help. Consider, for example, the command-line utility
1398    C<TransactFeatures>. It accepts a list of positional parameters plus the options
1399    C<safe>, C<noAlias>, C<start>, and C<tblFiles>. To start up this command, we execute
1400    the following code.
1401    
1402        my ($options, @parameters) = Tracer::StandardSetup(["DocUtils"],
1403                            { safe => [0, "use database transactions"],
1404                              noAlias => [0, "do not expect aliases in CHANGE transactions"],
1405                              start => [' ', "start with this genome"],
1406                              tblFiles => [0, "output TBL files containing the corrected IDs"] },
1407                            "<command> <transactionDirectory> <IDfile>",
1408                          @ARGV);
1409    
1410    
1411    The call to C<ParseCommand> specifies the default values for the options and
1412    stores the actual options in a hash that is returned as C<$options>. The
1413    positional parameters are returned in C<@parameters>.
1414    
1415    The following is a sample command line for C<TransactFeatures>.
1416    
1417        TransactFeatures -trace=2 -noAlias register ../xacts IDs.tbl
1418    
1419    Single and double hyphens are equivalent. So, you could also code the
1420    above command as
1421    
1422        TransactFeatures --trace=2 --noAlias register ../xacts IDs.tbl
1423    
1424    In this case, C<register>, C<../xacts>, and C<IDs.tbl> are the positional
1425    parameters, and would find themselves in I<@parameters> after executing the
1426    above code fragment. The tracing would be set to level 2, and the categories
1427    would be C<Tracer>, and <DocUtils>. C<Tracer> is standard,
1428    and C<DocUtils> was included because it came in within the first parameter
1429    to this method. The I<$options> hash would be
1430    
1431        { trace => 2, sql => 0, safe => 0,
1432          noAlias => 1, start => ' ', tblFiles => 0 }
1433    
1434    Use of C<StandardSetup> in this way provides a simple way of performing
1435    standard tracing setup and command-line parsing. Note that the caller is
1436    not even aware of the command-line switches C<-trace> and C<-sql>, which
1437    are used by this method to control the tracing. If additional tracing features
1438    need to be added in the future, they can be processed by this method without
1439    upsetting the command-line utilities.
1440    
1441    If the C<background> option is specified on the command line, then the
1442    standard and error outputs will be directed to files in the temporary
1443    directory, using the same suffix as the trace file. So, if the command
1444    line specified
1445    
1446        -user=Bruce -background
1447    
1448    then the trace output would go to C<traceBruce.log>, the standard output to
1449    C<outBruce.log>, and the error output to C<errBruce.log>. This is designed to
1450    simplify starting a command in the background.
1451    
1452    The user name is also used as the tracing key for L</Emergency Tracing>.
1453    Specifying a value of C<E> for the trace level causes emergency tracing to
1454    be used instead of custom tracing. If the user name is not specified,
1455    the tracing key is taken from the C<Tracing> environment variable. If there
1456    is no value for that variable, the tracing key will be computed from the PID.
1457    
1458    Finally, if the special option C<-help> is specified, the option
1459    names will be traced at level 0 and the program will exit without processing.
1460    This provides a limited help capability. For example, if the user enters
1461    
1462        TransactFeatures -help
1463    
1464    he would see the following output.
1465    
1466        TransactFeatures [options] <command> <transactionDirectory> <IDfile>
1467            -trace    tracing level (default E)
1468            -sql      trace SQL commands
1469            -safe     use database transactions
1470            -noAlias  do not expect aliases in CHANGE transactions
1471            -start    start with this genome
1472            -tblFiles output TBL files containing the corrected IDs
1473    
1474    The caller has the option of modifying the tracing scheme by placing a value
1475    for C<trace> in the incoming options hash. The default value can be overridden,
1476    or the tracing to the standard output can be turned off by suffixing a minus
1477    sign to the trace level. So, for example,
1478    
1479        { trace => [0, "tracing level (default 0)"],
1480           ...
1481    
1482    would set the default trace level to 0 instead of E, while
1483    
1484        { trace => ["2-", "tracing level (default 2)"],
1485           ...
1486    
1487    would set the default to 2, but trace only to the log file, not to the
1488    standard output.
1489    
1490    The parameters to this method are as follows.
1491    
1492    =over 4
1493    
1494    =item categories
1495    
1496    Reference to a list of tracing category names. These should be names of
1497    packages whose internal workings will need to be debugged to get the
1498    command working.
1499    
1500    =item options
1501    
1502    Reference to a hash containing the legal options for the current command mapped
1503    to their default values and descriptions. The user can override the defaults
1504    by specifying the options as command-line switches prefixed by a hyphen.
1505    Tracing-related options may be added to this hash. If the C<-h> option is
1506    specified on the command line, the option descriptions will be used to
1507    explain the options. To turn off tracing to the standard output, add a
1508    minus sign to the value for C<trace> (see above).
1509    
1510    =item parmHelp
1511    
1512    A string that vaguely describes the positional parameters. This is used
1513    if the user specifies the C<-h> option.
1514    
1515    =item argv
1516    
1517    List of command line parameters, including the option switches, which must
1518    precede the positional parameters and be prefixed by a hyphen.
1519    
1520    =item RETURN
1521    
1522    Returns a list. The first element of the list is the reference to a hash that
1523    maps the command-line option switches to their values. These will either be the
1524    default values or overrides specified on the command line. The remaining
1525    elements of the list are the position parameters, in order.
1526    
1527    =back
1528    
1529    =cut
1530    
1531    sub StandardSetup {
1532        # Get the parameters.
1533        my ($categories, $options, $parmHelp, @argv) = @_;
1534        # Get the default tracing key.
1535        my $tkey = EmergencyKey();
1536        # Add the tracing options.
1537        if (! exists $options->{trace}) {
1538            $options->{trace} = ['2', "tracing level (E for emergency tracing)"];
1539        }
1540        $options->{sql} = [0, "turn on SQL tracing"];
1541        $options->{help} = [0, "display command-line options"];
1542        $options->{user} = [$tkey, "tracing key"];
1543        $options->{background} = [0, "spool standard and error output"];
1544        # Create a parsing hash from the options hash. The parsing hash
1545        # contains the default values rather than the default value
1546        # and the description. While we're at it, we'll memorize the
1547        # length of the longest option name.
1548        my $longestName = 0;
1549        my %parseOptions = ();
1550        for my $key (keys %{$options}) {
1551            if (length $key > $longestName) {
1552                $longestName = length $key;
1553            }
1554            $parseOptions{$key} = $options->{$key}->[0];
1555        }
1556        # Parse the command line.
1557        my ($retOptions, @retParameters) = ParseCommand(\%parseOptions, @argv);
1558        # Get the logfile suffix.
1559        my $suffix = $retOptions->{user};
1560        # Check for background mode.
1561        if ($retOptions->{background}) {
1562            my $outFileName = "$FIG_Config::temp/out$suffix.log";
1563            my $errFileName = "$FIG_Config::temp/err$suffix.log";
1564            open STDOUT, ">$outFileName";
1565            open STDERR, ">$errFileName";
1566            # Check for phone support. If we have phone support and a phone number,
1567            # we want to turn it on.
1568            if ($ENV{PHONE} && defined($FIG_Config::phone)) {
1569                $retOptions->{phone} = $ENV{PHONE};
1570            }
1571        }
1572        # Now we want to set up tracing. First, we need to know if the user
1573        # wants emergency tracing.
1574        if ($retOptions->{trace} eq 'E') {
1575            ETracing($retOptions->{user});
1576        } else {
1577            # Here the tracing is controlled from the command line.
1578            my @cats = @{$categories};
1579            if ($retOptions->{sql}) {
1580                push @cats, "SQL";
1581            }
1582            # Add the default categories.
1583            push @cats, "Tracer";
1584            # Next, we create the category string by joining the categories.
1585            my $cats = join(" ", @cats);
1586            # Check to determine whether or not the caller wants to turn off tracing
1587            # to the standard output.
1588            my $traceLevel = $retOptions->{trace};
1589            my $textOKFlag = 1;
1590            if ($traceLevel =~ /^(.)-/) {
1591                $traceLevel = $1;
1592                $textOKFlag = 0;
1593            }
1594            # Now we set up the trace mode.
1595            my $traceMode;
1596            # Verify that we can open a file in the FIG temporary directory.
1597            my $traceFileName = "$FIG_Config::temp/trace$suffix.log";
1598            if (open TESTTRACE, ">$traceFileName") {
1599                # Here we can trace to a file.
1600                $traceMode = ">$traceFileName";
1601                if ($textOKFlag) {
1602                    # Echo to standard output if the text-OK flag is set.
1603                    $traceMode = "+$traceMode";
1604                }
1605                # Close the test file.
1606                close TESTTRACE;
1607            } else {
1608                # Here we can't trace to a file. We trace to the standard output if it's
1609                # okay, and the error log otherwise.
1610                if ($textOKFlag) {
1611                    $traceMode = "TEXT";
1612                } else {
1613                    $traceMode = "WARN";
1614                }
1615            }
1616            # Now set up the tracing.
1617            TSetup("$traceLevel $cats", $traceMode);
1618        }
1619        # Check for the "help" option. If it is specified, dump the command-line
1620        # options and exit the program.
1621        if ($retOptions->{help}) {
1622            $0 =~ m#[/\\](\w+)(\.pl)?$#i;
1623            print "$1 [options] $parmHelp\n";
1624            for my $key (sort keys %{$options}) {
1625                my $name = Pad($key, $longestName, 0, ' ');
1626                my $desc = $options->{$key}->[1];
1627                if ($options->{$key}->[0]) {
1628                    $desc .= " (default " . $options->{$key}->[0] . ")";
1629                }
1630                print "  $name $desc\n";
1631            }
1632            exit(0);
1633        }
1634        # Trace the options, if applicable.
1635        if (T(3)) {
1636            my @parms = grep { $retOptions->{$_} } keys %{$retOptions};
1637            Trace("Selected options: " . join(", ", sort @parms) . ".");
1638        }
1639        # Return the parsed parameters.
1640        return ($retOptions, @retParameters);
1641  }  }
1642    
1643  =head3 ParseCommand  =head3 ReadOptions
   
 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); >>  
   
 In this case, the list @words will be treated as a command line. There are two options available,  
 B<errors> and B<logFile>. If @words has the following format  
   
 C<< -logFile=error.log apple orange rutabaga >>  
   
 then at the end of the invocation, C<$options> will be  
1644    
1645  C<< { errors => 0, logFile => 'error.log' } >>      my %options = Tracer::ReadOptions($fileName);
1646    
1647  and C<@arguments> will contain  Read a set of options from a file. Each option is encoded in a line of text that has the
1648    format
1649    
1650  C<< apple orange rutabaga >>  I<optionName>C<=>I<optionValue>C<; >I<comment>
1651    
1652  The parser allows for some escape sequences. See L</UnEscape> for a description. There is no  The option name must consist entirely of letters, digits, and the punctuation characters
1653  support for quote characters.  C<.> and C<_>, and is case sensitive. Blank lines and lines in which the first nonblank
1654    character is a semi-colon will be ignored. The return hash will map each option name to
1655    the corresponding option value.
1656    
1657  =over 4  =over 4
1658    
1659  =item optionTable  =item fileName
   
 Table of default options.  
   
 =item inputList  
1660    
1661  List of words on the command line.  Name of the file containing the option data.
1662    
1663  =item RETURN  =item RETURN
1664    
1665  Returns a reference to the option table and a list of the positional arguments.  Returns a hash mapping the option names specified in the file to their corresponding option
1666    value.
1667    
1668  =back  =back
1669    
1670  =cut  =cut
1671    
1672  sub ParseCommand {  sub ReadOptions {
1673      # Get the parameters.      # Get the parameters.
1674      my ($optionTable, @inputList) = @_;      my ($fileName) = @_;
1675      # Process any options in the input list.      # Open the file.
1676      my %overrides = ();      (open CONFIGFILE, "<$fileName") || Confess("Could not open option file $fileName.");
1677      while ((@inputList > 0) && ($inputList[0] =~ /^-/)) {      # Count the number of records read.
1678          # Get the current option.      my ($records, $comments) = 0;
1679          my $arg = shift @inputList;      # Create the return hash.
1680          # Pull out the option name.      my %retVal = ();
1681          $arg =~ /^-([^=]*)/g;      # Loop through the file, accumulating key-value pairs.
1682          my $name = $1;      while (my $line = <CONFIGFILE>) {
1683          # Check for an option value.          # Denote we've read a line.
1684          if ($arg =~ /\G=(.*)$/g) {          $records++;
1685              # Here we have a value for the option.          # Determine the line type.
1686              $overrides{$name} = UnEscape($1);          if ($line =~ /^\s*[\n\r]/) {
1687                # A blank line is a comment.
1688                $comments++;
1689            } elsif ($line =~ /^\s*([A-Za-z0-9_\.]+)=([^;]*);/) {
1690                # Here we have an option assignment.
1691                retVal{$1} = $2;
1692            } elsif ($line =~ /^\s*;/) {
1693                # Here we have a text comment.
1694                $comments++;
1695          } else {          } else {
1696              # Here there is no value, so we use 1.              # Here we have an invalid line.
1697              $overrides{$name} = 1;              Trace("Invalid option statement in record $records.") if T(0);
         }  
1698      }      }
     # Merge the options into the defaults.  
     GetOptions($optionTable, \%overrides);  
     # Translate the remaining parameters.  
     my @retVal = ();  
     for my $inputParm (@inputList) {  
         push @retVal, UnEscape($inputParm);  
1699      }      }
1700      # Return the results.      # Return the hash created.
1701      return ($optionTable, @retVal);      return %retVal;
1702  }  }
1703    
1704  =head3 Escape  =head3 GetOptions
   
 C<< my $codedString = Tracer::Escape($realString); >>  
   
 Escape a string for use in a command length. Tabs will be replaced by C<\t>, new-lines  
 replaced by C<\n>, carriage returns will be deleted, and backslashes will be doubled. The  
 result is to reverse the effect of L</UnEscape>.  
   
 =over 4  
   
 =item realString  
1705    
1706  String to escape.      Tracer::GetOptions(\%defaults, \%options);
1707    
1708  =item RETURN  Merge a specified set of options into a table of defaults. This method takes two hash references
1709    as input and uses the data from the second to update the first. If the second does not exist,
1710    there will be no effect. An error will be thrown if one of the entries in the second hash does not
1711    exist in the first.
1712    
1713  Escaped equivalent of the real string.  Consider the following example.
1714    
1715  =back      my $optionTable = GetOptions({ dbType => 'mySQL', trace => 0 }, $options);
1716    
1717  =cut  In this example, the variable B<$options> is expected to contain at most two options-- B<dbType> and
1718    B<trace>. The default database type is C<mySQL> and the default trace level is C<0>. If the value of
1719    B<$options> is C<< {dbType => 'Oracle'} >>, then the database type will be changed to C<Oracle> and
1720    the trace level will remain at 0. If B<$options> is undefined, then the database type and trace level
1721    will remain C<mySQL> and C<0>. If, on the other hand, B<$options> is defined as
1722    
1723  sub Escape {      {databaseType => 'Oracle'}
     # Get the parameter.  
     my ($realString) = @_;  
     # Initialize the return variable.  
     my $retVal = "";  
     # Loop through the parameter string, looking for sequences to escape.  
     while (length $realString > 0) {  
         # Look for the first sequence to escape.  
         if ($realString =~ /^(.*?)([\n\t\r\\])/) {  
             # Here we found it. The text preceding the sequence is in $1. The sequence  
             # itself is in $2. First, move the clear text to the return variable.  
             $retVal .= $1;  
             # Strip the processed section off the real string.  
             $realString = substr $realString, (length $2) + (length $1);  
             # Get the matched character.  
             my $char = $2;  
             # If we have a CR, we are done.  
             if ($char ne "\r") {  
                 # It's not a CR, so encode the escape sequence.  
                 $char =~ tr/\t\n/tn/;  
                 $retVal .= "\\" . $char;  
             }  
         } else {  
             # Here there are no more escape sequences. The rest of the string is  
             # transferred unmodified.  
             $retVal .= $realString;  
             $realString = "";  
         }  
     }  
     # Return the result.  
     return $retVal;  
 }  
1724    
1725  =head3 UnEscape  an error will occur because the B<databaseType> option does not exist.
1726    
1727  C<< my $realString = Tracer::UnEscape($codedString); >>  =over 4
1728    
1729  Replace escape sequences with their actual equivalents. C<\t> will be replaced by  =item defaults
 a tab, C<\n> by a new-line character, and C<\\> by a backslash. C<\r> codes will  
 be deleted.  
1730    
1731  =over 4  Table of default option values.
1732    
1733  =item codedString  =item options
1734    
1735  String to un-escape.  Table of overrides, if any.
1736    
1737  =item RETURN  =item RETURN
1738    
1739  Returns a copy of the original string with the escape sequences converted to their actual  Returns a reference to the default table passed in as the first parameter.
 values.  
1740    
1741  =back  =back
1742    
1743  =cut  =cut
1744    
1745  sub UnEscape {  sub GetOptions {
1746      # Get the parameter.      # Get the parameters.
1747      my ($codedString) = @_;      my ($defaults, $options) = @_;
1748      # Initialize the return variable.      # Check for overrides.
1749      my $retVal = "";      if ($options) {
1750      # Only proceed if the incoming string is nonempty.          # Loop through the overrides.
1751      if (defined $codedString) {          while (my ($option, $setting) = each %{$options}) {
1752          # Loop through the parameter string, looking for escape sequences. We can't do              # Insure this override exists.
1753          # translating because it causes problems with the escaped slash. ("\\t" becomes              if (!exists $defaults->{$option}) {
1754          # "\<tab>" no matter what we do.)                  croak "Unrecognized option $option encountered.";
         while (length $codedString > 0) {  
             # Look for the first escape sequence.  
             if ($codedString =~ /^(.*?)\\(\\|n|t|r)/) {  
                 # Here we found it. The text preceding the sequence is in $1. The sequence  
                 # itself is in $2. First, move the clear text to the return variable.  
                 $retVal .= $1;  
                 $codedString = substr $codedString, (2 + length $1);  
                 # Get the escape value.  
                 my $char = $2;  
                 # If we have a "\r", we are done.  
                 if ($char ne 'r') {  
                     # Here it's not an 'r', so we convert it.  
                     $char =~ tr/\\tn/\\\t\n/;  
                     $retVal .= $char;  
                 }  
1755              } else {              } else {
1756                  # Here there are no more escape sequences. The rest of the string is                  # Apply the override.
1757                  # transferred unmodified.                  $defaults->{$option} = $setting;
                 $retVal .= $codedString;  
                 $codedString = "";  
1758              }              }
1759          }          }
1760      }      }
1761      # Return the result.      # Return the merged table.
1762      return $retVal;      return $defaults;
1763  }  }
1764    
1765  =head3 ParseRecord  =head3 MergeOptions
1766    
1767  C<< my @fields = Tracer::ParseRecord($line); >>      Tracer::MergeOptions(\%table, \%defaults);
1768    
1769  Parse a tab-delimited data line. The data line is split into field values. Embedded tab  Merge default values into a hash table. This method looks at the key-value pairs in the
1770  and new-line characters in the data line must be represented as C<\t> and C<\n>, respectively.  second (default) hash, and if a matching key is not found in the first hash, the default
1771  These will automatically be converted.  pair is copied in. The process is similar to L</GetOptions>, but there is no error-
1772    checking and no return value.
1773    
1774  =over 4  =over 4
1775    
1776  =item line  =item table
1777    
1778  Line of data containing the tab-delimited fields.  Hash table to be updated with the default values.
1779    
1780  =item RETURN  =item defaults
1781    
1782  Returns a list of the fields found in the data line.  Default values to be merged into the first hash table if they are not already present.
1783    
1784  =back  =back
1785    
1786  =cut  =cut
1787    
1788  sub ParseRecord {  sub MergeOptions {
1789      # Get the parameter.      # Get the parameters.
1790      my ($line) = @_;      my ($table, $defaults) = @_;
1791      # Remove the trailing new-line, if any.      # Loop through the defaults.
1792      chomp $line;      while (my ($key, $value) = each %{$defaults}) {
1793      # Split the line read into pieces using the tab character.          if (!exists $table->{$key}) {
1794      my @retVal = split /\t/, $line;              $table->{$key} = $value;
1795      # 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;  
1796      }      }
     # Return the result.  
     return @retVal;  
1797  }  }
1798    
1799  =head3 Merge  =head3 ParseCommand
   
 C<< my @mergedList = Tracer::Merge(@inputList); >>  
   
 Sort a list of strings and remove duplicates.  
   
 =over 4  
1800    
1801  =item inputList      my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList);
1802    
1803  List of scalars to sort and merge.  Parse a command line consisting of a list of parameters. The initial parameters may be option
1804    specifiers of the form C<->I<option> or C<->I<option>C<=>I<value>. The options are stripped
1805    off and merged into a table of default options. The remainder of the command line is
1806    returned as a list of positional arguments. For example, consider the following invocation.
1807    
1808  =item RETURN      my ($options, @arguments) = ParseCommand({ errors => 0, logFile => 'trace.log'}, @words);
1809    
1810  Returns a list containing the same elements sorted in ascending order with duplicates  In this case, the list @words will be treated as a command line and there are two options available,
1811  removed.  B<errors> and B<logFile>. If @words has the following format
1812    
1813  =back      -logFile=error.log apple orange rutabaga
1814    
1815  =cut  then at the end of the invocation, C<$options> will be
1816    
1817  sub Merge {      { errors => 0, logFile => 'error.log' }
     # 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;  
 }  
1818    
1819  =head3 Percent  and C<@arguments> will contain
1820    
1821  C<< my $percent = Tracer::Percent($number, $base); >>      apple orange rutabaga
1822    
1823  Returns the percent of the base represented by the given number. If the base  The parser allows for some escape sequences. See L</UnEscape> for a description. There is no
1824  is zero, returns zero.  support for quote characters. Options can be specified with single or double hyphens.
1825    
1826  =over 4  =over 4
1827    
1828  =item number  =item optionTable
1829    
1830  Percent numerator.  Table of default options.
1831    
1832  =item base  =item inputList
1833    
1834  Percent base.  List of words on the command line.
1835    
1836  =item RETURN  =item RETURN
1837    
1838  Returns the percentage of the base represented by the numerator.  Returns a reference to the option table and a list of the positional arguments.
1839    
1840  =back  =back
1841    
1842  =cut  =cut
1843    
1844  sub Percent {  sub ParseCommand {
1845      # Get the parameters.      # Get the parameters.
1846      my ($number, $base) = @_;      my ($optionTable, @inputList) = @_;
1847      # Declare the return variable.      # Process any options in the input list.
1848      my $retVal = 0;      my %overrides = ();
1849      # Compute the percent.      while ((@inputList > 0) && ($inputList[0] =~ /^--?/)) {
1850      if ($base != 0) {          # Get the current option.
1851          $retVal = $number * 100 / $base;          my $arg = shift @inputList;
1852            # Pull out the option name.
1853            $arg =~ /^--?([^=]*)/g;
1854            my $name = $1;
1855            # Check for an option value.
1856            if ($arg =~ /\G=(.*)$/g) {
1857                # Here we have a value for the option.
1858                $overrides{$name} = UnEscape($1);
1859            } else {
1860                # Here there is no value, so we use 1.
1861                $overrides{$name} = 1;
1862      }      }
1863      # Return the result.      }
1864      return $retVal;      # Merge the options into the defaults.
1865        GetOptions($optionTable, \%overrides);
1866        # Translate the remaining parameters.
1867        my @retVal = ();
1868        for my $inputParm (@inputList) {
1869            push @retVal, UnEscape($inputParm);
1870        }
1871        # Return the results.
1872        return ($optionTable, @retVal);
1873  }  }
1874    
1875    
1876    =head2 File Utility Methods
1877    
1878  =head3 GetFile  =head3 GetFile
1879    
1880  C<< my @fileContents = Tracer::GetFile($fileName); >>      my @fileContents = Tracer::GetFile($fileName);
1881    
1882      or      or
1883    
1884  C<< my $fileContents = Tracer::GetFile($fileName); >>      my $fileContents = Tracer::GetFile($fileName);
1885    
1886  Return the entire contents of a file. In list context, line-ends are removed and  Return the entire contents of a file. In list context, line-ends are removed and
1887  each line is a list element. In scalar context, line-ends are replaced by C<\n>.  each line is a list element. In scalar context, line-ends are replaced by C<\n>.
# Line 1436  Line 1920 
1920      # Close it.      # Close it.
1921      close $handle;      close $handle;
1922      my $actualLines = @retVal;      my $actualLines = @retVal;
1923        Trace("$actualLines lines read from file $fileName.") if T(File => 2);
1924      # Return the file's contents in the desired format.      # Return the file's contents in the desired format.
1925      if (wantarray) {      if (wantarray) {
1926          return @retVal;          return @retVal;
# Line 1446  Line 1931 
1931    
1932  =head3 PutFile  =head3 PutFile
1933    
1934  C<< Tracer::PutFile($fileName, \@lines); >>      Tracer::PutFile($fileName, \@lines);
1935    
1936  Write out a file from a list of lines of text.  Write out a file from a list of lines of text.
1937    
# Line 1471  Line 1956 
1956      my ($fileName, $lines) = @_;      my ($fileName, $lines) = @_;
1957      # Open the output file.      # Open the output file.
1958      my $handle = Open(undef, ">$fileName");      my $handle = Open(undef, ">$fileName");
1959        # Count the lines written.
1960      if (ref $lines ne 'ARRAY') {      if (ref $lines ne 'ARRAY') {
1961          # Here we have a scalar, so we write it raw.          # Here we have a scalar, so we write it raw.
1962          print $handle $lines;          print $handle $lines;
1963            Trace("Scalar put to file $fileName.") if T(File => 3);
1964      } else {      } else {
1965          # Write the lines one at a time.          # Write the lines one at a time.
1966            my $count = 0;
1967          for my $line (@{$lines}) {          for my $line (@{$lines}) {
1968              print $handle "$line\n";              print $handle "$line\n";
1969                $count++;
1970          }          }
1971            Trace("$count lines put to file $fileName.") if T(File => 3);
1972      }      }
1973      # Close the output file.      # Close the output file.
1974      close $handle;      close $handle;
1975  }  }
1976    
1977  =head3 QTrace  =head3 ParseRecord
   
 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  
   
 =item message  
   
 Message to include in the trace.  
   
 =back  
   
 =cut  
   
 sub Confess {  
     # Get the parameters.  
     my ($message) = @_;  
     # Trace the call stack.  
     Cluck($message);  
     # Abort the program.  
     croak(">>> $message");  
 }  
   
 =head3 Assert  
   
 C<< Assert($condition1, $condition2, ... $conditionN); >>  
   
 Return TRUE if all the conditions are true. This method can be used in conjunction with  
 the OR operator and the L</Confess> method as a debugging assert.  
 So, for example  
   
 C<< Assert($recNum >= 0) || Confess("Invalid record number $recNum."); >>  
   
 Will abort the program with a stack trace if the value of C<$recNum> is negative.  
   
 =cut  
 sub Assert {  
     my $retVal = 1;  
     LOOP: for my $condition (@_) {  
         if (! $condition) {  
             $retVal = 0;  
             last LOOP;  
         }  
     }  
     return $retVal;  
 }  
   
 =head3 Cluck  
   
 C<< Cluck($message); >>  
   
 Trace the call stack. Note that for best results, you should qualify the call with a  
 trace condition. For example,  
   
 C<< Cluck("Starting record parse.") if T(3); >>  
   
 will only trace the stack if the trace level for the package is 3 or more.  
   
 =over 4  
   
 =item message  
   
 Message to include in the trace.  
   
 =back  
   
 =cut  
   
 sub Cluck {  
     # Get the parameters.  
     my ($message) = @_;  
     # Trace what's happening.  
     Trace("Stack trace for event: $message");  
     my $confession = longmess($message);  
     # Convert the confession to a series of trace messages. Note we skip any  
     # messages relating to calls into Tracer.  
     for my $line (split /\s*\n/, $confession) {  
         Trace($line) if ($line !~ /Tracer\.pm/);  
     }  
 }  
   
 =head3 Min  
1978    
1979  C<< my $min = Min($value1, $value2, ... $valueN); >>      my @fields = Tracer::ParseRecord($line);
1980    
1981  Return the minimum argument. The arguments are treated as numbers.  Parse a tab-delimited data line. The data line is split into field values. Embedded tab
1982    and new-line characters in the data line must be represented as C<\t> and C<\n>, respectively.
1983    These will automatically be converted.
1984    
1985  =over 4  =over 4
1986    
1987  =item $value1, $value2, ... $valueN  =item line
1988    
1989  List of numbers to compare.  Line of data containing the tab-delimited fields.
1990    
1991  =item RETURN  =item RETURN
1992    
1993  Returns the lowest number in the list.  Returns a list of the fields found in the data line.
1994    
1995  =back  =back
1996    
1997  =cut  =cut
1998    
1999  sub Min {  sub ParseRecord {
2000      # Get the parameters. Note that we prime the return value with the first parameter.      # Get the parameter.
2001      my ($retVal, @values) = @_;      my ($line) = @_;
2002      # Loop through the remaining parameters, looking for the lowest.      # Remove the trailing new-line, if any.
2003      for my $value (@values) {      chomp $line;
2004          if ($value < $retVal) {      # Split the line read into pieces using the tab character.
2005              $retVal = $value;      my @retVal = split /\t/, $line;
2006          }      # Trim and fix the escapes in each piece.
2007        for my $value (@retVal) {
2008            # Trim leading whitespace.
2009            $value =~ s/^\s+//;
2010            # Trim trailing whitespace.
2011            $value =~ s/\s+$//;
2012            # Delete the carriage returns.
2013            $value =~ s/\r//g;
2014            # Convert the escapes into their real values.
2015            $value =~ s/\\t/"\t"/ge;
2016            $value =~ s/\\n/"\n"/ge;
2017      }      }
2018      # Return the minimum found.      # Return the result.
2019      return $retVal;      return @retVal;
2020  }  }
2021    
2022  =head3 Max  =head3 Merge
2023    
2024  C<< my $max = Max($value1, $value2, ... $valueN); >>      my @mergedList = Tracer::Merge(@inputList);
2025    
2026  Return the maximum argument. The arguments are treated as numbers.  Sort a list of strings and remove duplicates.
2027    
2028  =over 4  =over 4
2029    
2030  =item $value1, $value2, ... $valueN  =item inputList
2031    
2032  List of numbers to compare.  List of scalars to sort and merge.
2033    
2034  =item RETURN  =item RETURN
2035    
2036  Returns the highest number in the list.  Returns a list containing the same elements sorted in ascending order with duplicates
2037    removed.
2038    
2039  =back  =back
2040    
2041  =cut  =cut
2042    
2043  sub Max {  sub Merge {
2044      # Get the parameters. Note that we prime the return value with the first parameter.      # Get the input list in sort order.
2045      my ($retVal, @values) = @_;      my @inputList = sort @_;
2046      # Loop through the remaining parameters, looking for the highest.      # Only proceed if the list has at least two elements.
2047      for my $value (@values) {      if (@inputList > 1) {
2048          if ($value > $retVal) {          # Now we want to move through the list splicing out duplicates.
2049              $retVal = $value;          my $i = 0;
2050            while ($i < @inputList) {
2051                # Get the current entry.
2052                my $thisEntry = $inputList[$i];
2053                # Find out how many elements duplicate the current entry.
2054                my $j = $i + 1;
2055                my $dup1 = $i + 1;
2056                while ($j < @inputList && $inputList[$j] eq $thisEntry) { $j++; };
2057                # If the number is nonzero, splice out the duplicates found.
2058                if ($j > $dup1) {
2059                    splice @inputList, $dup1, $j - $dup1;
2060                }
2061                # Now the element at position $dup1 is different from the element before it
2062                # at position $i. We push $i forward one position and start again.
2063                $i++;
2064          }          }
2065      }      }
2066      # Return the maximum found.      # Return the merged list.
2067      return $retVal;      return @inputList;
2068  }  }
2069    
2070  =head3 AddToListMap  =head3 Open
2071    
2072  C<< Tracer::AddToListMap(\%hash, $key, $value1, $value2, ... valueN); >>      my $handle = Open($fileHandle, $fileSpec, $message);
2073    
2074  Add a key-value pair to a hash of lists. If no value exists for the key, a singleton list  Open a file.
 is created for the key. Otherwise, the new value is pushed onto the list.  
2075    
2076  =over 4  The I<$fileSpec> is essentially the second argument of the PERL C<open>
2077    function. The mode is specified using Unix-like shell information. So, for
2078    example,
2079    
2080  =item hash      Open(\*LOGFILE, '>>/usr/spool/news/twitlog', "Could not open twit log.");
2081    
2082  Reference to the target hash.  would open for output appended to the specified file, and
2083    
2084  =item key      Open(\*DATASTREAM, "| sort -u >$outputFile", "Could not open $outputFile.");
2085    
2086  Key for which the value is to be added.  would open a pipe that sorts the records written and removes duplicates. Note
2087    the use of file handle syntax in the Open call. To use anonymous file handles,
2088    code as follows.
2089    
2090  =item value1, value2, ... valueN      my $logFile = Open(undef, '>>/usr/spool/news/twitlog', "Could not open twit log.");
2091    
2092  List of values to add to the key's value list.  The I<$message> parameter is used if the open fails. If it is set to C<0>, then
2093    the open returns TRUE if successful and FALSE if an error occurred. Otherwise, a
2094    failed open will throw an exception and the third parameter will be used to construct
2095    an error message. If the parameter is omitted, a standard message is constructed
2096    using the file spec.
2097    
2098  =back      Could not open "/usr/spool/news/twitlog"
2099    
2100  =cut  Note that the mode characters are automatically cleaned from the file name.
2101    The actual error message from the file system will be captured and appended to the
2102    message in any case.
2103    
2104  sub AddToListMap {      Could not open "/usr/spool/news/twitlog": file not found.
2105      # Get the parameters.  
2106      my ($hash, $key, @values) = @_;  In some versions of PERL the only error message we get is a number, which
2107      # Process according to whether or not the key already has a value.  corresponds to the C++ C<errno> value.
2108      if (! exists $hash->{$key}) {  
2109          $hash->{$key} = [@values];      Could not open "/usr/spool/news/twitlog": 6.
2110      } else {  
2111          push @{$hash->{$key}}, @values;  =over 4
2112      }  
2113  }  =item fileHandle
2114    
2115    File handle. If this parameter is C<undef>, a file handle will be generated
2116    and returned as the value of this method.
2117    
2118    =item fileSpec
2119    
2120    File name and mode, as per the PERL C<open> function.
2121    
2122    =item message (optional)
2123    
2124  =head3 DebugMode  Error message to use if the open fails. If omitted, a standard error message
2125    will be generated. In either case, the error information from the file system
2126    is appended to the message. To specify a conditional open that does not throw
2127    an error if it fails, use C<0>.
2128    
2129  C<< if (Tracer::DebugMode) { ...code... } >>  =item RETURN
2130    
2131  Return TRUE if debug mode has been turned on, else abort.  Returns the name of the file handle assigned to the file, or C<undef> if the
2132    open failed.
2133    
2134  Certain CGI scripts are too dangerous to exist in the production  =back
 environment. This method provides a simple way to prevent them  
 from working unless they are explicitly turned on by creating a password  
 cookie via the B<SetPassword> script.  If debugging mode  
 is not turned on, an error will occur.  
2135    
2136  =cut  =cut
2137    
2138  sub DebugMode {  sub Open {
2139      # Declare the return variable.      # Get the parameters.
2140      my $retVal = 0;      my ($fileHandle, $fileSpec, $message) = @_;
2141      # Check the debug configuration.      # Attempt to open the file.
2142      my $password = CGI::cookie("DebugMode");      my $rv = open $fileHandle, $fileSpec;
2143      my $encrypted = Digest::MD5::md5_hex($password);      # If the open failed, generate an error message.
2144      if ($encrypted eq "252dec43280e0c0d6a75ffcec486e61d") {      if (! $rv) {
2145          $retVal = 1;          # Save the system error message.
2146      } else {          my $sysMessage = $!;
2147          # Here debug mode is off, so we generate an error.          # See if we need a default message.
2148          Confess("Cannot use this facility without logging in.");          if (!$message) {
2149                # Clean any obvious mode characters and leading spaces from the
2150                # filename.
2151                my ($fileName) = FindNamePart($fileSpec);
2152                $message = "Could not open \"$fileName\"";
2153      }      }
2154      # Return the determination indicator.          # Terminate with an error using the supplied message and the
2155      return $retVal;          # error message from the file system.
2156            Confess("$message: $!");
2157        }
2158        # Return the file handle.
2159        return $fileHandle;
2160  }  }
2161    
2162  =head3 Strip  =head3 FindNamePart
2163    
2164  C<< my $string = Tracer::Strip($line); >>      my ($fileName, $start, $len) = Tracer::FindNamePart($fileSpec);
2165    
2166  Strip all line terminators off a string. This is necessary when dealing with files  Extract the portion of a file specification that contains the file name.
2167  that may have been transferred back and forth several times among different  
2168  operating environments.  A file specification is the string passed to an C<open> call. It specifies the file
2169    mode and name. In a truly complex situation, it can specify a pipe sequence. This
2170    method assumes that the file name is whatever follows the first angle bracket
2171    sequence.  So, for example, in the following strings the file name is
2172    C</usr/fig/myfile.txt>.
2173    
2174        >>/usr/fig/myfile.txt
2175        </usr/fig/myfile.txt
2176        | sort -u > /usr/fig/myfile.txt
2177    
2178    If the method cannot find a file name using its normal methods, it will return the
2179    whole incoming string.
2180    
2181  =over 4  =over 4
2182    
2183  =item line  =item fileSpec
2184    
2185  Line of text to be stripped.  File specification string from which the file name is to be extracted.
2186    
2187  =item RETURN  =item RETURN
2188    
2189  The same line of text with all the line-ending characters chopped from the end.  Returns a three-element list. The first element contains the file name portion of
2190    the specified string, or the whole string if a file name cannot be found via normal
2191    methods. The second element contains the start position of the file name portion and
2192    the third element contains the length.
2193    
2194  =back  =back
2195    
2196  =cut  =cut
2197    #: Return Type $;
2198  sub Strip {  sub FindNamePart {
2199      # Get a copy of the parameter string.      # Get the parameters.
2200      my ($string) = @_;      my ($fileSpec) = @_;
2201      my $retVal = (defined $string ? $string : "");      # Default to the whole input string.
2202      # Strip the line terminator characters.      my ($retVal, $pos, $len) = ($fileSpec, 0, length $fileSpec);
2203      $retVal =~ s/(\r|\n)+$//g;      # Parse out the file name if we can.
2204        if ($fileSpec =~ m/(<|>>?)(.+?)(\s*)$/) {
2205            $retVal = $2;
2206            $len = length $retVal;
2207            $pos = (length $fileSpec) - (length $3) - $len;
2208        }
2209      # Return the result.      # Return the result.
2210      return $retVal;      return ($retVal, $pos, $len);
2211  }  }
2212    
2213  =head3 Pad  =head3 OpenDir
2214    
2215  C<< my $paddedString = Tracer::Pad($string, $len, $left, $padChar); >>      my @files = OpenDir($dirName, $filtered, $flag);
2216    
2217  Pad a string to a specified length. The pad character will be a  Open a directory and return all the file names. This function essentially performs
2218  space, and the padding will be on the right side unless specified  the functions of an C<opendir> and C<readdir>. If the I<$filtered> parameter is
2219  in the third parameter.  set to TRUE, all filenames beginning with a period (C<.>), dollar sign (C<$>),
2220    or pound sign (C<#>) and all filenames ending with a tilde C<~>) will be
2221    filtered out of the return list. If the directory does not open and I<$flag> is not
2222    set, an exception is thrown. So, for example,
2223    
2224  =over 4      my @files = OpenDir("/Volumes/fig/contigs", 1);
2225    
2226  =item string  is effectively the same as
2227    
2228  String to be padded.      opendir(TMP, "/Volumes/fig/contigs") || Confess("Could not open /Volumes/fig/contigs.");
2229        my @files = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir(TMP);
2230    
2231  =item len  Similarly, the following code
2232    
2233  Desired length of the padded string.      my @files = grep { $_ =~ /^\d/ } OpenDir("/Volumes/fig/orgs", 0, 1);
2234    
2235  =item left (optional)  Returns the names of all files in C</Volumes/fig/orgs> that begin with digits and
2236    automatically returns an empty list if the directory fails to open.
2237    
2238  TRUE if the string is to be left-padded; otherwise it will be padded on the right.  =over 4
2239    
2240  =item padChar (optional)  =item dirName
2241    
2242  Character to use for padding. The default is a space.  Name of the directory to open.
2243    
2244  =item RETURN  =item filtered
2245    
2246  Returns a copy of the original string with the pad character added to the  TRUE if files whose names begin with a period (C<.>) should be automatically removed
2247  specified end so that it achieves the desired length.  from the list, else FALSE.
2248    
2249    =item flag
2250    
2251    TRUE if a failure to open is okay, else FALSE
2252    
2253  =back  =back
2254    
2255  =cut  =cut
2256    #: Return Type @;
2257  sub Pad {  sub OpenDir {
2258      # Get the parameters.      # Get the parameters.
2259      my ($string, $len, $left, $padChar) = @_;      my ($dirName, $filtered, $flag) = @_;
2260      # Compute the padding character.      # Declare the return variable.
2261      if (! defined $padChar) {      my @retVal = ();
2262          $padChar = " ";      # Open the directory.
2263      }      if (opendir(my $dirHandle, $dirName)) {
2264      # Compute the number of spaces needed.          # The directory opened successfully. Get the appropriate list according to the
2265      my $needed = $len - length $string;          # strictures of the filter parameter.
2266      # Copy the string into the return variable.          if ($filtered) {
2267      my $retVal = $string;              @retVal = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir $dirHandle;
     # Only proceed if padding is needed.  
     if ($needed > 0) {  
         # Create the pad string.  
         my $pad = $padChar x $needed;  
         # Affix it to the return value.  
         if ($left) {  
             $retVal = $pad . $retVal;  
2268          } else {          } else {
2269              $retVal .= $pad;              @retVal = readdir $dirHandle;
2270          }          }
2271        } elsif (! $flag) {
2272            # Here the directory would not open and it's considered an error.
2273            Confess("Could not open directory $dirName.");
2274      }      }
2275      # Return the result.      # Return the result.
2276      return $retVal;      return @retVal;
2277  }  }
2278    
 =head3 EOF  
2279    
2280  This is a constant that is lexically greater than any useful string.  =head3 Insure
2281    
2282  =cut      Insure($dirName, $chmod);
2283    
2284    Insure a directory is present.
2285    
2286    =over 4
2287    
2288  sub EOF {  =item dirName
     return "\xFF\xFF\xFF\xFF\xFF";  
 }  
2289    
2290  =head3 TICK  Name of the directory to check. If it does not exist, it will be created.
2291    
2292  C<< my @results = TICK($commandString); >>  =item chmod (optional)
2293    
2294  Perform a back-tick operation on a command. If this is a Windows environment, any leading  Security privileges to be given to the directory if it is created.
 dot-slash (C<./> will be removed. So, for example, if you were doing  
2295    
2296      `./protein.cgi`  =back
2297    
2298  from inside a CGI script, it would work fine in Unix, but would issue an error message  =cut
 in Windows complaining that C<'.'> is not a valid command. If instead you code  
2299    
2300      TICK("./protein.cgi")  sub Insure {
2301        my ($dirName, $chmod) = @_;
2302        if (! -d $dirName) {
2303            Trace("Creating $dirName directory.") if T(2);
2304            eval {
2305                mkpath $dirName;
2306                # If we have permissions specified, set them here.
2307                if (defined($chmod)) {
2308                    chmod $chmod, $dirName;
2309                }
2310            };
2311            if ($@) {
2312                Confess("Error creating $dirName: $@");
2313            }
2314        }
2315    }
2316    
2317  it will work correctly in both environments.  =head3 ChDir
2318    
2319  =over 4      ChDir($dirName);
2320    
2321  =item commandString  Change to the specified directory.
2322    
2323  The command string to pass to the system.  =over 4
2324    
2325  =item RETURN  =item dirName
2326    
2327  Returns the standard output from the specified command, as a list.  Name of the directory to which we want to change.
2328    
2329  =back  =back
2330    
2331  =cut  =cut
2332  #: Return Type @;  
2333  sub TICK {  sub ChDir {
2334      # Get the parameters.      my ($dirName) = @_;
2335      my ($commandString) = @_;      if (! -d $dirName) {
2336      # Chop off the dot-slash if this is Windows.          Confess("Cannot change to directory $dirName: no such directory.");
2337      if ($FIG_Config::win_mode) {      } else {
2338          $commandString =~ s!^\./!!;          Trace("Changing to directory $dirName.") if T(File => 4);
2339            my $okFlag = chdir $dirName;
2340            if (! $okFlag) {
2341                Confess("Error switching to directory $dirName.");
2342            }
2343      }      }
     # Activate the command and return the result.  
     return `$commandString`;  
2344  }  }
2345    
2346  =head3 ScriptSetup  =head3 SetPermissions
2347    
2348  C<< my ($cgi, $varHash) = ScriptSetup($noTrace); >>      Tracer::SetPermissions($dirName, $group, $mask, %otherMasks);
2349    
2350  Perform standard tracing and debugging setup for scripts. The value returned is  Set the permissions for a directory and all the files and folders inside it.
2351  the CGI object followed by a pre-built variable hash.  In addition, the group ownership will be changed to the specified value.
2352    
2353  The C<Trace> query parameter is used to determine whether or not tracing is active and  This method is more vulnerable than most to permission and compatability
2354  which trace modules (other than C<Tracer> itself) should be turned on. Specifying  problems, so it does internal error recovery.
 the C<CGI> trace module will trace parameter and environment information. Parameters are  
 traced at level 3 and environment variables at level 4. To trace to a file instead of to  
 the web page, set C<TF> to 1. At the end of the script, the client should call  
 L</ScriptFinish> to output the web page.  
   
 In some situations, it is not practical to invoke tracing via form parameters. For this  
 situation, you can turn on emergency tracing by invoking the L</Emergency> method from  
 a web page. Emergency tracing is detected via a file with the name  
 C<Emergency>I<IPaddr>C<.txt> in the FIG temporary directory, where I<IPaddr> is the  
 IP address of the remote user who wants tracing turned on. The file contains a time  
 limit in hours on the first line, a tracing destination on the second line, a trace  
 level on the third line, and the tracing modules on subsequent lines.  
2355    
2356  =over 4  =over 4
2357    
2358  =item noTrace (optional)  =item dirName
2359    
2360  If specified, tracing will be suppressed. This is useful if the script wants to set up  Name of the directory to process.
 tracing manually.  
2361    
2362  =item RETURN  =item group
2363    
2364  Returns a two-element list consisting of a CGI query object and a variable hash for  Name of the group to be assigned.
2365  the output page.  
2366    =item mask
2367    
2368    Permission mask. Bits that are C<1> in this mask will be ORed into the
2369    permission bits of any file or directory that does not already have them
2370    set to 1.
2371    
2372    =item otherMasks
2373    
2374    Map of search patterns to permission masks. If a directory name matches
2375    one of the patterns, that directory and all its members and subdirectories
2376    will be assigned the new pattern. For example, the following would
2377    assign 01664 to most files, but would use 01777 for directories named C<tmp>.
2378    
2379        Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp$' => 01777);
2380    
2381    The list is ordered, so the following would use 0777 for C<tmp1> and
2382    0666 for C<tmp>, C<tmp2>, or C<tmp3>.
2383    
2384        Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp1' => 0777,
2385                                                       '^tmp' => 0666);
2386    
2387    Note that the pattern matches are all case-insensitive, and only directory
2388    names are matched, not file names.
2389    
2390  =back  =back
2391    
2392  =cut  =cut
2393    
2394  sub ScriptSetup {  sub SetPermissions {
2395      # Get the parameters.      # Get the parameters.
2396      my ($noTrace) = @_;      my ($dirName, $group, $mask, @otherMasks) = @_;
2397      # Get the CGI query object.      # Set up for error recovery.
2398      my $cgi = CGI->new();      eval {
2399      # Set up tracing if it's not suppressed.          # Switch to the specified directory.
2400      CGITrace($cgi) unless $noTrace;          ChDir($dirName);
2401      # Create the variable hash.          # Get the group ID.
2402      my $varHash = { results => '' };          my $gid = getgrnam($group);
2403      # Return the query object and variable hash.          # Get the mask for tracing.
2404      return ($cgi, $varHash);          my $traceMask = sprintf("%04o", $mask) . "($mask)";
2405            Trace("Fixing permissions for directory $dirName using group $group($gid) and mask $traceMask.") if T(File => 2);
2406            my $fixCount = 0;
2407            my $lookCount = 0;
2408            # @dirs will be a stack of directories to be processed.
2409            my @dirs = (getcwd());
2410            while (scalar(@dirs) > 0) {
2411                # Get the current directory.
2412                my $dir = pop @dirs;
2413                # Check for a match to one of the specified directory names. To do
2414                # that, we need to pull the individual part of the name off of the
2415                # whole path.
2416                my $simpleName = $dir;
2417                if ($dir =~ m!/([^/]+)$!) {
2418                    $simpleName = $1;
2419                }
2420                Trace("Simple directory name for $dir is $simpleName.") if T(File => 4);
2421                # Search for a match.
2422                my $match = 0;
2423                my $i;
2424                for ($i = 0; $i < $#otherMasks && ! $match; $i += 2) {
2425                    my $pattern = $otherMasks[$i];
2426                    if ($simpleName =~ /$pattern/i) {
2427                        $match = 1;
2428                    }
2429                }
2430                # Check for a match. Note we use $i-1 because the loop added 2
2431                # before terminating due to the match.
2432                if ($match && $otherMasks[$i-1] != $mask) {
2433                    # This directory matches one of the incoming patterns, and it's
2434                    # a different mask, so we process it recursively with that mask.
2435                    SetPermissions($dir, $group, $otherMasks[$i-1], @otherMasks);
2436                } else {
2437                    # Here we can process normally. Get all of the non-hidden members.
2438                    my @submems = OpenDir($dir, 1);
2439                    for my $submem (@submems) {
2440                        # Get the full name.
2441                        my $thisMem = "$dir/$submem";
2442                        Trace("Checking member $thisMem.") if T(4);
2443                        $lookCount++;
2444                        if ($lookCount % 1000 == 0) {
2445                            Trace("$lookCount members examined. Current is $thisMem. Mask is $traceMask") if T(File => 3);
2446                        }
2447                        # Fix the group.
2448                        chown -1, $gid, $thisMem;
2449                        # Insure this member is not a symlink.
2450                        if (! -l $thisMem) {
2451                            # Get its info.
2452                            my $fileInfo = stat $thisMem;
2453                            # Only proceed if we got the info. Otherwise, it's a hard link
2454                            # and we want to skip it anyway.
2455                            if ($fileInfo) {
2456                                my $fileMode = $fileInfo->mode;
2457                                if (($fileMode & $mask) != $mask) {
2458                                    # Fix this member.
2459                                    $fileMode |= $mask;
2460                                    chmod $fileMode, $thisMem;
2461                                    $fixCount++;
2462                                }
2463                                # If it's a subdirectory, stack it.
2464                                if (-d $thisMem) {
2465                                    push @dirs, $thisMem;
2466                                }
2467                            }
2468                        }
2469                    }
2470                }
2471            }
2472            Trace("$lookCount files and directories processed, $fixCount fixed.") if T(File => 2);
2473        };
2474        # Check for an error.
2475        if ($@) {
2476            Confess("SetPermissions error: $@");
2477        }
2478  }  }
2479    
2480  =head3 CGITrace  =head3 GetLine
2481    
2482  C<< Tracer::CGITrace($cgi); >>      my @data = Tracer::GetLine($handle);
2483    
2484  Set up tracing for a CGI script. See L</ScriptSetup> for more information.  Read a line of data from a tab-delimited file.
2485    
2486  =over 4  =over 4
2487    
2488  =item cgi  =item handle
2489    
2490    Open file handle from which to read.
2491    
2492    =item RETURN
2493    
2494  Ths CGI query object for this script.  Returns a list of the fields in the record read. The fields are presumed to be
2495    tab-delimited. If we are at the end of the file, then an empty list will be
2496    returned. If an empty line is read, a single list item consisting of a null
2497    string will be returned.
2498    
2499  =back  =back
2500    
2501  =cut  =cut
2502    
2503  sub CGITrace {  sub GetLine {
2504      # Get the parameters.      # Get the parameters.
2505      my ($cgi) = @_;      my ($handle) = @_;
2506      # Default to no tracing except errors.      # Declare the return variable.
2507      my ($tracing, $dest) = ("0", "WARN");      my @retVal = ();
2508      # Check for emergency tracing.      Trace("File position is " . tell($handle) . ". EOF flag is " . eof($handle) . ".") if T(File => 4);
2509      my $ip = EmergencyIP($cgi);      # Read from the file.
2510      my $emergencyFile = EmergencyFileName($ip);      my $line = <$handle>;
2511      if (-e $emergencyFile) {      # Only proceed if we found something.
2512          # We have the file. Read in the data.      if (defined $line) {
2513          my @tracing = GetFile($emergencyFile);          # Remove the new-line. We are a bit over-cautious here because the file may be coming in via an
2514          # Pull off the time limit.          # upload control and have a nonstandard EOL combination.
2515          my $expire = shift @tracing;          $line =~ s/(\r|\n)+$//;
2516          # Convert it to seconds.          # Here we do some fancy tracing to help in debugging complicated EOL marks.
2517          $expire *= 3600;          if (T(File => 4)) {
2518          # Check the file data.              my $escapedLine = $line;
2519          my $stat = stat($emergencyFile);              $escapedLine =~ s/\n/\\n/g;
2520          my ($now) = gettimeofday;              $escapedLine =~ s/\r/\\r/g;
2521          if ($now - $stat->mtime > $expire) {              $escapedLine =~ s/\t/\\t/g;
2522              # Delete the expired file.              Trace("Line read: -->$escapedLine<--");
2523              unlink $emergencyFile;          }
2524            # If the line is empty, return a single empty string; otherwise, parse
2525            # it into fields.
2526            if ($line eq "") {
2527                push @retVal, "";
2528          } else {          } else {
2529              # Emergency tracing is on. Pull off the destination and              push @retVal, split /\t/,$line;
             # the trace level;  
             $dest = shift @tracing;  
             my $level = shift @tracing;  
             # Convert the destination to a real tracing destination.  
             # temp directory.  
             $dest = EmergencyTracingDest($ip, $dest);  
             # Insure Tracer is specified.  
             my %moduleHash = map { $_ => 1 } @tracing;  
             $moduleHash{Tracer} = 1;  
             # Set the trace parameter.  
             $tracing = join(" ", $level, sort keys %moduleHash);  
             # Make sure the script knows tracing is on.  
             $cgi->param(-name => 'Trace', -value => $tracing);  
             $cgi->param(-name => 'TF', -value => (($dest =~ /^>/) ? 1 : 0));  
2530          }          }
2531      } elsif ($cgi->param('Trace')) {      } else {
2532          # Here the user has requested tracing via a form.          # Trace the reason the read failed.
2533          $dest = ($cgi->param('TF') ? ">$FIG_Config::temp/Trace$$.log" : "QUEUE");          Trace("End of file: $!") if T(File => 3);
         $tracing = $cgi->param('Trace') . " Tracer";  
2534      }      }
2535      # Setup the tracing we've determined from all the stuff above.      # Return the result.
2536      TSetup($tracing, $dest);      return @retVal;
     # Trace the parameter and environment data.  
     TraceParms($cgi);  
2537  }  }
2538    
2539  =head3 EmergencyFileName  =head3 PutLine
2540    
2541  C<< my $fileName = Tracer::EmergencyFileName($ip); >>      Tracer::PutLine($handle, \@fields, $eol);
2542    
2543  Return the emergency tracing file name. This is the file that specifies  Write a line of data to a tab-delimited file. The specified field values will be
2544  the tracing information.  output in tab-separated form, with a trailing new-line.
2545    
2546  =over 4  =over 4
2547    
2548  =item ip  =item handle
2549    
2550    Output file handle.
2551    
2552    =item fields
2553    
2554  IP address of the user who wants tracing, as taken from the C<< $cgi->remote_host() >>  List of field values.
 method.  
2555    
2556  =item RETURN  =item eol (optional)
2557    
2558  Returns the name of the file to contain the emergency tracing information.  End-of-line character (default is "\n").
2559    
2560  =back  =back
2561    
2562  =cut  =cut
2563    
2564  sub EmergencyFileName {  sub PutLine {
2565      # Get the parameters.      # Get the parameters.
2566      my ($ip) = @_;      my ($handle, $fields, $eol) = @_;
2567      # Compute the emergency tracing file name.      # Write the data.
2568      return "$FIG_Config::temp/Emergency$ip.txt";      print $handle join("\t", @{$fields}) . ($eol || "\n");
2569  }  }
2570    
 =head3 EmergencyFileTarget  
   
 C<< my $fileName = Tracer::EmergencyFileTarget($ip); >>  
2571    
2572  Return the emergency tracing target file name. This is the file that receives  =head3 PrintLine
 the tracing output for file-based tracing.  
2573    
2574  =over 4      Tracer::PrintLine($line);
2575    
2576  =item ip  Print a line of text with a trailing new-line.
2577    
2578  IP address of the user who wants tracing, as taken from the C<< $cgi->remote_host() >>  =over 4
 method.  
2579    
2580  =item RETURN  =item line
2581    
2582  Returns the name of the file to contain the emergency tracing information.  Line of text to print.
2583    
2584  =back  =back
2585    
2586  =cut  =cut
2587    
2588  sub EmergencyFileTarget {  sub PrintLine {
2589      # Get the parameters.      # Get the parameters.
2590      my ($ip) = @_;      my ($line) = @_;
2591      # Compute the emergency tracing file name.      # Print the line.
2592      return "$FIG_Config::temp/Emergency$ip.log";      print "$line\n";
2593  }  }
2594    
 =head3 EmergencyTracingDest  
2595    
2596  C<< my $dest = Tracer::EmergencyTracingDest($ip, $myDest); >>  =head2 Other Useful Methods
2597    
2598  This method converts an emergency tracing destination to a real  =head3 ParseParm
 tracing destination. The main difference is that if the  
 destination is C<FILE> or C<APPEND>, we convert it to file  
 output.  
2599    
2600  =over 4      my $listValue = Tracer::ParseParm($string);
2601    
2602  =item ip  Convert a parameter into a list reference. If the parameter is undefined,
2603    an undefined value will be returned. Otherwise, it will be parsed as a
2604    comma-separated list of values.
2605    
2606  IP address of the user who wants tracing, as taken from the C<< $cgi->remote_host() >>  =over 4
 method.  
2607    
2608  =item myDest  =item string
2609    
2610  Destination from the emergency tracing file.  Incoming string.
2611    
2612  =item RETURN  =item RETURN
2613    
2614  Returns a destination that can be passed into L</TSetup>.  Returns a reference to a list of values, or C<undef> if the incoming value
2615    was undefined.
2616    
2617  =back  =back
2618    
2619  =cut  =cut
2620    
2621  sub EmergencyTracingDest {  sub ParseParm {
2622      # Get the parameters.      # Get the parameters.
2623      my ($ip, $myDest) = @_;      my ($string) = @_;
2624      # Declare the return variable.      # Declare the return variable.
2625      my $retVal;      my $retVal;
2626      # Process according to the destination value.      # Check for data.
2627      if ($myDest eq 'FILE') {      if (defined $string) {
2628          $retVal = ">" . EmergencyFileTarget($ip);          # We have some, so split it into a list.
2629      } elsif ($myDest eq 'APPEND') {          $retVal = [ split /\s*,\s*/, $string];
         $retVal = ">>" . EmergencyFileTarget($ip);  
     } else {  
         $retVal = $myDest;  
2630      }      }
2631      # Return the result.      # Return the result.
2632      return $retVal;      return $retVal;
2633  }  }
2634    
2635  =head3 Emergency  =head3 Now
   
 C<< Emergency($cgi, $hours, $dest, $level, @modules); >>  
2636    
2637  Turn on emergency tracing. This method can only be invoked over the web and is      my $string = Tracer::Now();
 should not be called if debug mode is off. The caller specifies the duration of the  
 emergency in hours, the desired tracing destination, the trace level,  
 and a list of the trace modules to activate. For the duration, when a user  
 from the specified remote web location invokes a Sprout CGI script, tracing  
 will be turned on automatically. See L</TSetup> for more about tracing  
 setup and L</ScriptSetup> for more about emergency tracing.  
2638    
2639  =over 4  Return a displayable time stamp containing the local time. Whatever format this
2640    method produces must be parseable by L</ParseDate>.
2641    
2642  =item cgi  =cut
2643    
2644  A CGI query object.  sub Now {
2645        return DisplayTime(time);
2646    }
2647    
2648  =item hours  =head3 DisplayTime
2649    
2650  Number of hours to keep emergency tracing alive.      my $string = Tracer::DisplayTime($time);
2651    
2652  =item dest  Convert a time value to a displayable time stamp. Whatever format this
2653    method produces must be parseable by L</ParseDate>.
2654    
2655  Tracing destination. If no path information is specified for a file  =over 4
 destination, it is put in the FIG temporary directory.  
2656    
2657  =item level  =item time
2658    
2659  Tracing level. A higher level means more trace messages.  Time to display, in seconds since the epoch, or C<undef> if the time is unknown.
2660    
2661  =item modules  =item RETURN
2662    
2663  A list of the tracing modules to activate.  Returns a displayable time, or C<(n/a)> if the incoming time is undefined.
2664    
2665  =back  =back
2666    
2667  =cut  =cut
2668    
2669  sub Emergency {  sub DisplayTime {
2670      # Get the parameters.      my ($time) = @_;
2671      my ($cgi, $hours, $dest, $level, @modules) = @_;      my $retVal = "(n/a)";
2672      # Get the IP address.      if (defined $time) {
2673      my $ip = EmergencyIP($cgi);          my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time);
2674      # Create the emergency file.          $retVal = _p2($mon+1) . "/" . _p2($mday) . "/" . ($year + 1900) . " " .
2675      my $specFile = EmergencyFileName($ip);                    _p2($hour) . ":" . _p2($min) . ":" . _p2($sec);
2676      my $outHandle = Open(undef, ">$specFile");      }
2677      print $outHandle join("\n",$hours, $dest, $level, @modules, "");      return $retVal;
2678  }  }
2679    
2680  =head3 EmergencyIP  # Pad a number to 2 digits.
2681    sub _p2 {
2682        my ($value) = @_;
2683        $value = "0$value" if ($value < 10);
2684        return $value;
2685    }
2686    
2687    =head3 Escape
2688    
2689  C<< my $ip = EmergencyIP($cgi); >>      my $codedString = Tracer::Escape($realString);
2690    
2691  Return the IP address to be used for emergency tracing. If at smoe point we need  Escape a string for use in a command. Tabs will be replaced by C<\t>, new-lines
2692  to change the way we compute the IP address, or we decide to use something else,  replaced by C<\n>, carriage returns will be deleted, and backslashes will be doubled. The
2693  all we need to do is change this method.  result is to reverse the effect of L</UnEscape>.
2694    
2695  =over 4  =over 4
2696    
2697  =item cgi  =item realString
2698    
2699  CGI query object.  String to escape.
2700    
2701  =item RETURN  =item RETURN
2702    
2703  Returns the IP address to be used for labelling emergency tracing.  Escaped equivalent of the real string.
2704    
2705  =back  =back
2706    
2707  =cut  =cut
2708    
2709  sub EmergencyIP {  sub Escape {
2710      # Get the parameters.      # Get the parameter.
2711      my ($cgi) = @_;      my ($realString) = @_;
2712        # Initialize the return variable.
2713        my $retVal = "";
2714        # Loop through the parameter string, looking for sequences to escape.
2715        while (length $realString > 0) {
2716            # Look for the first sequence to escape.
2717            if ($realString =~ /^(.*?)([\n\t\r\\])/) {
2718                # Here we found it. The text preceding the sequence is in $1. The sequence
2719                # itself is in $2. First, move the clear text to the return variable.
2720                $retVal .= $1;
2721                # Strip the processed section off the real string.
2722                $realString = substr $realString, (length $2) + (length $1);
2723                # Get the matched character.
2724                my $char = $2;
2725                # If we have a CR, we are done.
2726                if ($char ne "\r") {
2727                    # It's not a CR, so encode the escape sequence.
2728                    $char =~ tr/\t\n/tn/;
2729                    $retVal .= "\\" . $char;
2730                }
2731            } else {
2732                # Here there are no more escape sequences. The rest of the string is
2733                # transferred unmodified.
2734                $retVal .= $realString;
2735                $realString = "";
2736            }
2737        }
2738      # Return the result.      # Return the result.
2739      return $cgi->remote_addr();      return $retVal;
2740  }  }
2741    
2742    =head3 UnEscape
2743    
2744  =head3 TraceParms      my $realString = Tracer::UnEscape($codedString);
   
 C<< Tracer::TraceParms($cgi); >>  
2745    
2746  Trace the CGI parameters at trace level CGI => 3 and the environment variables  Replace escape sequences with their actual equivalents. C<\t> will be replaced by
2747  at level CGI => 4.  a tab, C<\n> by a new-line character, and C<\\> by a backslash. C<\r> codes will
2748    be deleted.
2749    
2750  =over 4  =over 4
2751    
2752  =item cgi  =item codedString
2753    
2754  CGI query object containing the parameters to trace.  String to un-escape.
2755    
2756    =item RETURN
2757    
2758    Returns a copy of the original string with the escape sequences converted to their actual
2759    values.
2760    
2761  =back  =back
2762    
2763  =cut  =cut
2764    
2765  sub TraceParms {  sub UnEscape {
2766      # Get the parameters.      # Get the parameter.
2767      my ($cgi) = @_;      my ($codedString) = @_;
2768      if (T(CGI => 3)) {      # Initialize the return variable.
2769          # Here we want to trace the parameter data.      my $retVal = "";
2770          my @names = $cgi->param;      # Only proceed if the incoming string is nonempty.
2771          for my $parmName (sort @names) {      if (defined $codedString) {
2772              # Note we skip the Trace parameters, which are for our use only.          # Loop through the parameter string, looking for escape sequences. We can't do
2773              if ($parmName ne 'Trace' && $parmName ne 'TF') {          # translating because it causes problems with the escaped slash. ("\\t" becomes
2774                  my @values = $cgi->param($parmName);          # "\<tab>" no matter what we do.)
2775                  Trace("CGI: $parmName = " . join(", ", @values));          while (length $codedString > 0) {
2776              }              # Look for the first escape sequence.
2777                if ($codedString =~ /^(.*?)\\(\\|n|t|r)/) {
2778                    # Here we found it. The text preceding the sequence is in $1. The sequence
2779                    # itself is in $2. First, move the clear text to the return variable.
2780                    $retVal .= $1;
2781                    $codedString = substr $codedString, (2 + length $1);
2782                    # Get the escape value.
2783                    my $char = $2;
2784                    # If we have a "\r", we are done.
2785                    if ($char ne 'r') {
2786                        # Here it's not an 'r', so we convert it.
2787                        $char =~ tr/\\tn/\\\t\n/;
2788                        $retVal .= $char;
2789          }          }
2790          # Display the request method.              } else {
2791          my $method = $cgi->request_method();                  # Here there are no more escape sequences. The rest of the string is
2792          Trace("Method: $method");                  # transferred unmodified.
2793                    $retVal .= $codedString;
2794                    $codedString = "";
2795      }      }
     if (T(CGI => 4)) {  
         # Here we want the environment data too.  
         for my $envName (sort keys %ENV) {  
             Trace("ENV: $envName = $ENV{$envName}");  
2796          }          }
2797      }      }
2798        # Return the result.
2799        return $retVal;
2800  }  }
2801    
2802  =head3 ScriptFinish  =head3 Percent
2803    
2804  C<< ScriptFinish($webData, $varHash); >>      my $percent = Tracer::Percent($number, $base);
2805    
2806  Output a web page at the end of a script. Either the string to be output or the  Returns the percent of the base represented by the given number. If the base
2807  name of a template file can be specified. If the second parameter is omitted,  is zero, returns zero.
 it is assumed we have a string to be output; otherwise, it is assumed we have the  
 name of a template file. The template should have the variable C<DebugData>  
 specified in any form that invokes a standard script. If debugging mode is turned  
 on, a form field will be put in that allows the user to enter tracing data.  
 Trace messages will be placed immediately before the terminal C<BODY> tag in  
 the output, formatted as a list.  
2808    
2809  A typical standard script would loook like the following.  =over 4
2810    
2811      BEGIN {  =item number
2812          # Print the HTML header.  
2813          print "CONTENT-TYPE: text/html\n\n";  Percent numerator.
2814    
2815    =item base
2816    
2817    Percent base.
2818    
2819    =item RETURN
2820    
2821    Returns the percentage of the base represented by the numerator.
2822    
2823    =back
2824    
2825    =cut
2826    
2827    sub Percent {
2828        # Get the parameters.
2829        my ($number, $base) = @_;
2830        # Declare the return variable.
2831        my $retVal = 0;
2832        # Compute the percent.
2833        if ($base != 0) {
2834            $retVal = $number * 100 / $base;
2835        }
2836        # Return the result.
2837        return $retVal;
2838      }      }
     use Tracer;  
     use CGI;  
     use FIG;  
     # ... more uses ...  
2839    
2840      my ($cgi, $varHash) = ScriptSetup();  =head3 Constrain
2841      eval {  
2842          # ... get data from $cgi, put it in $varHash ...      my $constrained = Constrain($value, $min, $max);
2843      };  
2844      if ($@) {  Modify a numeric value to bring it to a point in between a maximum and a minimum.
2845          Trace("Script Error: $@") if T(0);  
2846    =over 4
2847    
2848    =item value
2849    
2850    Value to constrain.
2851    
2852    =item min (optional)
2853    
2854    Minimum permissible value. If this parameter is undefined, no minimum constraint will be applied.
2855    
2856    =item max (optional)
2857    
2858    Maximum permissible value. If this parameter is undefined, no maximum constraint will be applied.
2859    
2860    =item RETURN
2861    
2862    Returns the incoming value, constrained according to the other parameters.
2863    
2864    =back
2865    
2866    =cut
2867    
2868    sub Constrain {
2869        # Get the parameters.
2870        my ($value, $min, $max) = @_;
2871        # Declare the return variable.
2872        my $retVal = $value;
2873        # Apply the minimum constraint.
2874        if (defined $min && $retVal < $min) {
2875            $retVal = $min;
2876        }
2877        # Apply the maximum constraint.
2878        if (defined $max && $retVal > $max) {
2879            $retVal = $max;
2880        }
2881        # Return the result.
2882        return $retVal;
2883      }      }
     ScriptFinish("Html/MyTemplate.html", $varHash);  
2884    
2885  The idea here is that even if the script fails, you'll see trace messages and  =head3 Min
2886  useful output.  
2887        my $min = Min($value1, $value2, ... $valueN);
2888    
2889    Return the minimum argument. The arguments are treated as numbers.
2890    
2891  =over 4  =over 4
2892    
2893  =item webData  =item $value1, $value2, ... $valueN
2894    
2895  A string containing either the full web page to be written to the output or the  List of numbers to compare.
 name of a template file from which the page is to be constructed. If the name  
 of a template file is specified, then the second parameter must be present;  
 otherwise, it must be absent.  
2896    
2897  =item varHash (optional)  =item RETURN
2898    
2899  If specified, then a reference to a hash mapping variable names for a template  Returns the lowest number in the list.
 to their values. The template file will be read into memory, and variable markers  
 will be replaced by data in this hash reference.  
2900    
2901  =back  =back
2902    
2903  =cut  =cut
2904    
2905  sub ScriptFinish {  sub Min {
2906      # Get the parameters.      # Get the parameters. Note that we prime the return value with the first parameter.
2907      my ($webData, $varHash) = @_;      my ($retVal, @values) = @_;
2908      # Check for a template file situation.      # Loop through the remaining parameters, looking for the lowest.
2909      my $outputString;      for my $value (@values) {
2910      if (defined $varHash) {          if ($value < $retVal) {
2911          # Here we have a template file. We need to determine the template type.              $retVal = $value;
         my $template;  
         if ($FIG_Config::template_url && $webData =~ /\.php$/) {  
             $template = "$FIG_Config::template_url/$webData";  
         } else {  
             $template = "<<$webData";  
         }  
         $outputString = PageBuilder::Build($template, $varHash, "Html");  
     } else {  
         # Here the user gave us a raw string.  
         $outputString = $webData;  
     }  
     # Check for trace messages.  
     if ($Destination ne "NONE" && $TraceLevel > 0) {  
         # We have trace messages, so we want to put them at the end of the body. This  
         # is either at the end of the whole string or at the beginning of the BODY  
         # end-tag.  
         my $pos = length $outputString;  
         if ($outputString =~ m#</body>#gi) {  
             $pos = (pos $outputString) - 7;  
         }  
         # If the trace messages were queued, we unroll them. Otherwise, we display the  
         # destination.  
         my $traceHtml;  
         if ($Destination eq "QUEUE") {  
             $traceHtml = QTrace('Html');  
         } elsif ($Destination =~ /^>>(.+)$/) {  
             # Here the tracing output it to a file. We code it as a hyperlink so the user  
             # can copy the file name into the clipboard easily.  
             my $actualDest = $1;  
             $traceHtml = "<p>Tracing output to <a href=\"$actualDest\">$actualDest</a>.</p>\n";  
         } else {  
             # Here we have one of the special destinations.  
             $traceHtml = "<P>Tracing output type is $Destination.</p>\n";  
2912          }          }
         substr $outputString, $pos, 0, $traceHtml;  
2913      }      }
2914      # Write the output string.      # Return the minimum found.
2915      print $outputString;      return $retVal;
2916  }  }
2917    
2918  =head3 Insure  =head3 Max
2919    
2920  C<< Insure($dirName); >>      my $max = Max($value1, $value2, ... $valueN);
2921    
2922  Insure a directory is present.  Return the maximum argument. The arguments are treated as numbers.
2923    
2924  =over 4  =over 4
2925    
2926  =item dirName  =item $value1, $value2, ... $valueN
2927    
2928  Name of the directory to check. If it does not exist, it will be created.  List of numbers to compare.
2929    
2930    =item RETURN
2931    
2932    Returns the highest number in the list.
2933    
2934  =back  =back
2935    
2936  =cut  =cut
2937    
2938  sub Insure {  sub Max {
2939      my ($dirName) = @_;      # Get the parameters. Note that we prime the return value with the first parameter.
2940      if (! -d $dirName) {      my ($retVal, @values) = @_;
2941          Trace("Creating $dirName directory.") if T(2);      # Loop through the remaining parameters, looking for the highest.
2942          eval { mkpath $dirName; };      for my $value (@values) {
2943          if ($@) {          if ($value > $retVal) {
2944              Confess("Error creating $dirName: $@");              $retVal = $value;
2945          }          }
2946      }      }
2947        # Return the maximum found.
2948        return $retVal;
2949  }  }
2950    
 =head3 ChDir  
2951    
2952  C<< ChDir($dirName); >>  =head3 Strip
2953    
2954        my $string = Tracer::Strip($line);
2955    
2956  Change to the specified directory.  Strip all line terminators off a string. This is necessary when dealing with files
2957    that may have been transferred back and forth several times among different
2958    operating environments.
2959    
2960  =over 4  =over 4
2961    
2962  =item dirName  =item line
2963    
2964  Name of the directory to which we want to change.  Line of text to be stripped.
2965    
2966    =item RETURN
2967    
2968    The same line of text with all the line-ending characters chopped from the end.
2969    
2970  =back  =back
2971    
2972  =cut  =cut
2973    
2974  sub ChDir {  sub Strip {
2975      my ($dirName) = @_;      # Get a copy of the parameter string.
2976      if (! -d $dirName) {      my ($string) = @_;
2977          Confess("Cannot change to directory $dirName: no such directory.");      my $retVal = (defined $string ? $string : "");
2978      } else {      # Strip the line terminator characters.
2979          Trace("Changing to directory $dirName.") if T(4);      $retVal =~ s/(\r|\n)+$//g;
2980          my $okFlag = chdir $dirName;      # Return the result.
2981          if (! $okFlag) {      return $retVal;
             Confess("Error switching to directory $dirName.");  
         }  
     }  
2982  }  }
2983    
2984  =head3 SendSMS  =head3 Pad
2985    
2986  C<< my $msgID = Tracer::SendSMS($phoneNumber, $msg); >>      my $paddedString = Tracer::Pad($string, $len, $left, $padChar);
2987    
2988  Send a text message to a phone number using Clickatell. The FIG_Config file must contain the  Pad a string to a specified length. The pad character will be a
2989  user name, password, and API ID for the relevant account in the hash reference variable  space, and the padding will be on the right side unless specified
2990  I<$FIG_Config::phone>, using the keys C<user>, C<password>, and C<api_id>. For  in the third parameter.
 example, if the user name is C<BruceTheHumanPet>, the password is C<silly>, and the API ID  
 is C<2561022>, then the FIG_Config file must contain  
2991    
2992      $phone =  { user => 'BruceTheHumanPet',  =over 4
                 password => 'silly',  
                 api_id => '2561022' };  
2993    
2994  The original purpose of this method was to insure Bruce would be notified immediately when the  =item string
 Sprout Load terminates. Care should be taken if you do not wish Bruce to be notified immediately  
 when you call this method.  
2995    
2996  The message ID will be returned if successful, and C<undef> if an error occurs.  String to be padded.
2997    
2998  =over 4  =item len
2999    
3000  =item phoneNumber  Desired length of the padded string.
3001    
3002  Phone number to receive the message, in international format. A United States phone number  =item left (optional)
 would be prefixed by "1". A British phone number would be prefixed by "44".  
3003    
3004  =item msg  TRUE if the string is to be left-padded; otherwise it will be padded on the right.
3005    
3006  Message to send to the specified phone.  =item padChar (optional)
3007    
3008    Character to use for padding. The default is a space.
3009    
3010  =item RETURN  =item RETURN
3011    
3012  Returns the message ID if successful, and C<undef> if the message could not be sent.  Returns a copy of the original string with the pad character added to the
3013    specified end so that it achieves the desired length.
3014    
3015  =back  =back
3016    
3017  =cut  =cut
3018    
3019  sub SendSMS {  sub Pad {
3020      # Get the parameters.      # Get the parameters.
3021      my ($phoneNumber, $msg) = @_;      my ($string, $len, $left, $padChar) = @_;
3022      # Declare the return variable. If we do not change it, C<undef> will be returned.      # Compute the padding character.
3023      my $retVal;      if (! defined $padChar) {
3024      # Only proceed if we have phone support.          $padChar = " ";
3025      if (! defined $FIG_Config::phone) {      }
3026          Trace("Phone support not present in FIG_Config.") if T(1);      # Compute the number of spaces needed.
3027      } else {      my $needed = $len - length $string;
3028          # Get the phone data.      # Copy the string into the return variable.
3029          my $parms = $FIG_Config::phone;      my $retVal = $string;
3030          # Get the Clickatell URL.      # Only proceed if padding is needed.
3031          my $url = "http://api.clickatell.com/http/";      if ($needed > 0) {
3032          # Create the user agent.          # Create the pad string.
3033          my $ua = LWP::UserAgent->new;          my $pad = $padChar x $needed;
3034          # Request a Clickatell session.          # Affix it to the return value.
3035          my $resp = $ua->post("$url/sendmsg", { user => $parms->{user},          if ($left) {
3036                                       password => $parms->{password},              $retVal = $pad . $retVal;
                                      api_id => $parms->{api_id},  
                                      to => $phoneNumber,  
                                      text => $msg});  
         # Check for an error.  
         if (! $resp->is_success) {  
             Trace("Alert failed.") if T(1);  
         } else {  
             # Get the message ID.  
             my $rstring = $resp->content;  
             if ($rstring =~ /^ID:\s+(.*)$/) {  
                 $retVal = $1;  
3037              } else {              } else {
3038                  Trace("Phone attempt failed with $rstring") if T(1);              $retVal .= $pad;
3039              }              }
3040          }          }
3041        # Return the result.
3042        return $retVal;
3043    }
3044    
3045    =head3 EOF
3046    
3047    This is a constant that is lexically greater than any useful string.
3048    
3049    =cut
3050    
3051    sub EOF {
3052        return "\xFF\xFF\xFF\xFF\xFF";
3053    }
3054    
3055    =head3 TICK
3056    
3057        my @results = TICK($commandString);
3058    
3059    Perform a back-tick operation on a command. If this is a Windows environment, any leading
3060    dot-slash (C<./> will be removed. So, for example, if you were doing
3061    
3062        `./protein.cgi`
3063    
3064    from inside a CGI script, it would work fine in Unix, but would issue an error message
3065    in Windows complaining that C<'.'> is not a valid command. If instead you code
3066    
3067        TICK("./protein.cgi")
3068    
3069    it will work correctly in both environments.
3070    
3071    =over 4
3072    
3073    =item commandString
3074    
3075    The command string to pass to the system.
3076    
3077    =item RETURN
3078    
3079    Returns the standard output from the specified command, as a list.
3080    
3081    =back
3082    
3083    =cut
3084    #: Return Type @;
3085    sub TICK {
3086        # Get the parameters.
3087        my ($commandString) = @_;
3088        # Chop off the dot-slash if this is Windows.
3089        if ($FIG_Config::win_mode) {
3090            $commandString =~ s!^\./!!;
3091      }      }
3092      # Return the result.      # Activate the command and return the result.
3093      return $retVal;      return `$commandString`;
3094  }  }
3095    
3096    
3097  =head3 CommaFormat  =head3 CommaFormat
3098    
3099  C<< my $formatted = Tracer::CommaFormat($number); >>      my $formatted = Tracer::CommaFormat($number);
3100    
3101  Insert commas into a number.  Insert commas into a number.
3102    
# Line 2503  Line 3129 
3129      # Return the result.      # Return the result.
3130      return $retVal;      return $retVal;
3131  }  }
 =head3 SetPermissions  
   
 C<< Tracer::SetPermissions($dirName, $group, $mask, %otherMasks); >>  
   
 Set the permissions for a directory and all the files and folders inside it.  
 In addition, the group ownership will be changed to the specified value.  
   
 This method is more vulnerable than most to permission and compatability  
 problems, so it does internal error recovery.  
   
 =over 4  
   
 =item dirName  
   
 Name of the directory to process.  
   
 =item group  
   
 Name of the group to be assigned.  
   
 =item mask  
   
 Permission mask. Bits that are C<1> in this mask will be ORed into the  
 permission bits of any file or directory that does not already have them  
 set to 1.  
   
 =item otherMasks  
3132    
 Map of search patterns to permission masks. If a directory name matches  
 one of the patterns, that directory and all its members and subdirectories  
 will be assigned the new pattern. For example, the following would  
 assign 01664 to most files, but would use 01777 for directories named C<tmp>.  
   
     Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp$' => 01777);  
   
 The list is ordered, so the following would use 0777 for C<tmp1> and  
 0666 for C<tmp>, C<tmp2>, or C<tmp3>.  
   
     Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp1' => 0777,  
                                                    '^tmp' => 0666);  
   
 Note that the pattern matches are all case-insensitive, and only directory  
 names are matched, not file names.  
   
 =back  
   
 =cut  
   
 sub SetPermissions {  
     # Get the parameters.  
     my ($dirName, $group, $mask, @otherMasks) = @_;  
     # Set up for error recovery.  
     eval {  
         # Switch to the specified directory.  
         ChDir($dirName);  
         # Get the group ID.  
         my $gid = getgrnam($group);  
         # Get the mask for tracing.  
         my $traceMask = sprintf("%04o", $mask) . "($mask)";  
         Trace("Fixing permissions for directory $dirName using group $group($gid) and mask $traceMask.") if T(2);  
         my $fixCount = 0;  
         my $lookCount = 0;  
         # @dirs will be a stack of directories to be processed.  
         my @dirs = (getcwd());  
         while (scalar(@dirs) > 0) {  
             # Get the current directory.  
             my $dir = pop @dirs;  
             # Check for a match to one of the specified directory names. To do  
             # that, we need to pull the individual part of the name off of the  
             # whole path.  
             my $simpleName = $dir;  
             if ($dir =~ m!/([^/]+)$!) {  
                 $simpleName = $1;  
             }  
             Trace("Simple directory name for $dir is $simpleName.") if T(4);  
             # Search for a match.  
             my $match = 0;  
             my $i;  
             for ($i = 0; $i < $#otherMasks && ! $match; $i += 2) {  
                 my $pattern = $otherMasks[$i];  
                 if ($simpleName =~ /$pattern/i) {  
                     $match = 1;  
                 }  
             }  
             # Check for a match. Note we use $i-1 because the loop added 2  
             # before terminating due to the match.  
             if ($match && $otherMasks[$i-1] != $mask) {  
                 # This directory matches one of the incoming patterns, and it's  
                 # a different mask, so we process it recursively with that mask.  
                 SetPermissions($dir, $group, $otherMasks[$i-1], @otherMasks);  
             } else {  
                 # Here we can process normally. Get all of the non-hidden members.  
                 my @submems = OpenDir($dir, 1);  
                 for my $submem (@submems) {  
                     # Get the full name.  
                     my $thisMem = "$dir/$submem";  
                     Trace("Checking member $thisMem.") if T(4);  
                     $lookCount++;  
                     if ($lookCount % 1000 == 0) {  
                         Trace("$lookCount members examined. Current is $thisMem. Mask is $traceMask") if T(3);  
                     }  
                     # Fix the group.  
                     chown -1, $gid, $thisMem;  
                     # Insure this member is not a symlink.  
                     if (! -l $thisMem) {  
                         # Get its info.  
                         my $fileInfo = stat $thisMem;  
                         # Only proceed if we got the info. Otherwise, it's a hard link  
                         # and we want to skip it anyway.  
                         if ($fileInfo) {  
                             my $fileMode = $fileInfo->mode;  
                             if (($fileMode & $mask) != $mask) {  
                                 # Fix this member.  
                                 $fileMode |= $mask;  
                                 chmod $fileMode, $thisMem;  
                                 $fixCount++;  
                             }  
                             # If it's a subdirectory, stack it.  
                             if (-d $thisMem) {  
                                 push @dirs, $thisMem;  
                             }  
                         }  
                     }  
                 }  
             }  
         }  
         Trace("$lookCount files and directories processed, $fixCount fixed.") if T(2);  
     };  
     # Check for an error.  
     if ($@) {  
         Confess("SetPermissions error: $@");  
     }  
 }  
3133    
3134  =head3 CompareLists  =head3 CompareLists
3135    
3136  C<< my ($inserted, $deleted) = Tracer::CompareLists(\@newList, \@oldList, $keyIndex); >>      my ($inserted, $deleted) = Tracer::CompareLists(\@newList, \@oldList, $keyIndex);
3137    
3138  Compare two lists of tuples, and return a hash analyzing the differences. The lists  Compare two lists of tuples, and return a hash analyzing the differences. The lists
3139  are presumed to be sorted alphabetically by the value in the $keyIndex column.  are presumed to be sorted alphabetically by the value in the $keyIndex column.
# Line 2704  Line 3198 
3198      return ($inserted, $deleted);      return ($inserted, $deleted);
3199  }  }
3200    
3201  =head3 GetLine  =head3 GenerateURL
3202    
3203  C<< my @data = Tracer::GetLine($handle); >>      my $queryUrl = Tracer::GenerateURL($page, %parameters);
3204    
3205  Read a line of data from a tab-delimited file.  Generate a GET-style URL for the specified page with the specified parameter
3206    names and values. The values will be URL-escaped automatically. So, for
3207    example
3208    
3209        Tracer::GenerateURL("form.cgi", type => 1, string => "\"high pass\" or highway")
3210    
3211    would return
3212    
3213        form.cgi?type=1;string=%22high%20pass%22%20or%20highway
3214    
3215  =over 4  =over 4
3216    
3217  =item handle  =item page
3218    
3219  Open file handle from which to read.  Page URL.
3220    
3221    =item parameters
3222    
3223    Hash mapping parameter names to parameter values.
3224    
3225  =item RETURN  =item RETURN
3226    
3227  Returns a list of the fields in the record read. The fields are presumed to be  Returns a GET-style URL that goes to the specified page and passes in the
3228  tab-delimited. If we are at the end of the file, then an empty list will be  specified parameters and values.
 returned. If an empty line is read, a single list item consisting of a null  
 string will be returned.  
3229    
3230  =back  =back
3231    
3232  =cut  =cut
3233    
3234  sub GetLine {  sub GenerateURL {
3235      # Get the parameters.      # Get the parameters.
3236      my ($handle) = @_;      my ($page, %parameters) = @_;
3237      # Declare the return variable.      # Prime the return variable with the page URL.
3238      my @retVal = ();      my $retVal = $page;
3239      # Read from the file.      # Loop through the parameters, creating parameter elements in a list.
3240      my $line = <$handle>;      my @parmList = map { "$_=" . uri_escape($parameters{$_}) } keys %parameters;
3241      # Only proceed if we found something.      # If the list is nonempty, tack it on.
3242      if (defined $line) {      if (@parmList) {
3243          # Remove the new-line.          $retVal .= "?" . join(";", @parmList);
         chomp $line;  
         # If the line is empty, return a single empty string; otherwise, parse  
         # it into fields.  
         if ($line eq "") {  
             push @retVal, "";  
         } else {  
             push @retVal, split /\t/,$line;  
         }  
3244      }      }
3245      # Return the result.      # Return the result.
3246      return @retVal;      return $retVal;
3247  }  }
3248    
3249  =head3 PutLine  =head3 ApplyURL
3250    
3251  C<< Tracer::PutLine($handle, \@fields); >>      Tracer::ApplyURL($table, $target, $url);
3252    
3253  Write a line of data to a tab-delimited file. The specified field values will be  Run through a two-dimensional table (or more accurately, a list of lists), converting the
3254  output in tab-separated form, with a trailing new-line.  I<$target> column to HTML text having a hyperlink to a URL in the I<$url> column. The
3255    URL column will be deleted by this process and the target column will be HTML-escaped.
3256    
3257    This provides a simple way to process the results of a database query into something
3258    displayable by combining a URL with text.
3259    
3260  =over 4  =over 4
3261    
3262  =item handle  =item table
3263    
3264  Output file handle.  Reference to a list of lists. The elements in the containing list will be updated by
3265    this method.
3266    
3267  =item fields  =item target
3268    
3269  List of field values.  The index of the column to be converted into HTML.
3270    
3271    =item url
3272    
3273    The index of the column containing the URL. Note that the URL must have a recognizable
3274    C<http:> at the beginning.
3275    
3276  =back  =back
3277    
3278  =cut  =cut
3279    
3280  sub PutLine {  sub ApplyURL {
3281      # Get the parameters.      # Get the parameters.
3282      my ($handle, $fields) = @_;      my ($table, $target, $url) = @_;
3283      # Write the data.      # Loop through the table.
3284      print $handle join("\t", @{$fields}) . "\n";      for my $row (@{$table}) {
3285            # Apply the URL to the target cell.
3286            $row->[$target] = CombineURL($row->[$target], $row->[$url]);
3287            # Delete the URL from the row.
3288            delete $row->[$url];
3289        }
3290  }  }
3291    
3292  =head3 GenerateURL  =head3 CombineURL
3293    
3294  C<< my $queryUrl = Tracer::GenerateURL($page, %parameters); >>      my $combinedHtml = Tracer::CombineURL($text, $url);
3295    
3296  Generate a GET-style URL for the specified page with the specified parameter  This method will convert the specified text into HTML hyperlinked to the specified
3297  names and values. The values will be URL-escaped automatically. So, for  URL. The hyperlinking will only take place if the URL looks legitimate: that is, it
3298  example  is defined and begins with an C<http:> header.
3299    
3300      Tracer::GenerateURL("form.cgi", type => 1, string => "\"high pass\" or highway")  =over 4
3301    
3302  would return  =item text
3303    
3304    Text to return. This will be HTML-escaped automatically.
3305    
3306    =item url
3307    
3308    A URL to be hyperlinked to the text. If it does not look like a URL, then the text
3309    will be returned without any hyperlinking.
3310    
3311    =item RETURN
3312    
3313    Returns the original text, HTML-escaped, with the URL hyperlinked to it. If the URL
3314    doesn't look right, the HTML-escaped text will be returned without any further
3315    modification.
3316    
3317    =back
3318    
3319    =cut