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