[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.6, Mon Mar 7 02:01:51 2005 UTC revision 1.41, Wed Mar 15 21:59:29 2006 UTC
# Line 1  Line 1 
1    #
2    # Copyright (c) 2003-2006 University of Chicago and Fellowship
3    # for Interpretations of Genomes. All Rights Reserved.
4    #
5    # This file is part of the SEED Toolkit.
6    #
7    # The SEED Toolkit is free software. You can redistribute
8    # it and/or modify it under the terms of the SEED Toolkit
9    # Public License.
10    #
11    # You should have received a copy of the SEED Toolkit Public License
12    # along with this program; if not write to the University of Chicago
13    # at info@ci.uchicago.edu or the Fellowship for Interpretation of
14    # Genomes at veronika@thefig.info or download a copy from
15    # http://www.theseed.org/LICENSE.TXT.
16    #
17    
18  package Tracer;  package Tracer;
19    
20          require Exporter;          require Exporter;
21          @ISA = ('Exporter');          @ISA = ('Exporter');
22          @EXPORT = qw(Trace T TSetup QTrace Confess Cluck Min Max Assert);      @EXPORT = qw(Trace T TSetup QTrace Confess Cluck Min Max Assert Open OpenDir TICK StandardSetup ScriptSetup ScriptFinish Insure);
23          @EXPORT_OK = qw(GetFile GetOptions Merge MergeOptions ParseCommand ParseRecord UnEscape);      @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);
26          use CGI;          use CGI;
27        use FIG_Config;
28        use PageBuilder;
29        use Digest::MD5;
30        use File::Basename;
31        use File::Path;
32    
33  =head1 Tracing and Debugging Helpers  =head1 Tracing and Debugging Helpers
34    
# Line 18  Line 40 
40  has a list of categories and a single trace level set by the B<TSetup> method. Only messages whose trace  has a list of categories and a single trace level set by the B<TSetup> method. Only messages whose trace
41  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 this package's trace level and whose category is activated will
42  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
43  is less likely to be seen. A higher trace level passed to B<Setup> means more trace messages will  is less likely to be seen. A higher trace level passed to B<TSetup> means more trace messages will
44  appear. To generate a trace message, use the following syntax.  appear. To generate a trace message, use the following syntax.
45    
46  C<< Trace($message) if T(errors => 4); >>  C<< Trace($message) if T(errors => 4); >>
# Line 36  Line 58 
58    
59  C<< Trace($message) if T(2); >>  C<< Trace($message) if T(2); >>
60    
61  To set up tracing, you call the C</Setup> method. The method takes as input a trace level, a list  To set up tracing, you call the L</TSetup> method. The method takes as input a trace level, a list
62  of category names, and a set of options. The trace level and list of category names are  of category names, and a set of options. The trace level and list of category names are
63  specified as a space-delimited string. Thus  specified as a space-delimited string. Thus
64    
65  C<< TSetup('3 errors Sprout ERDB', 'HTML'); >>  C<< TSetup('3 errors Sprout ERDB', 'HTML'); >>
66    
67  sets the trace level to 3, activated 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
68  specifies that messages should be output as HTML paragraphs. The idea is to make it easier to  specifies that messages should be output as HTML paragraphs.
69  input tracing configuration on a web form.  
70    To turn on tracing for ALL categories, use an asterisk. The call below sets every category to
71    level 3 and writes the output to the standard error output. This sort of thing might be
72    useful in a CGI environment.
73    
74    C<< TSetup('3 *', 'WARN'); >>
75    
76  In addition to HTML and file output for trace messages, you can specify that the trace messages  In addition to HTML and file output for trace messages, you can specify that the trace messages
77  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
# Line 59  Line 86 
86  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
87  being used out in the field.  being used out in the field.
88    
89    There is no hard and fast rule on how to use trace levels. The following is therefore only
90    a suggestion.
91    
92    =over 4
93    
94    =item Error 0
95    
96    Message indicates an error that may lead to incorrect results or that has stopped the
97    application entirely.
98    
99    =item Warning 1
100    
101    Message indicates something that is unexpected but that probably did not interfere
102    with program execution.
103    
104    =item Notice 2
105    
106    Message indicates the beginning or end of a major task.
107    
108    =item Information 3
109    
110    Message indicates a subtask. In the FIG system, a subtask generally relates to a single
111    genome. This would be a big loop that is not expected to execute more than 500 times or so.
112    
113    =item Detail 4
114    
115    Message indicates a low-level loop iteration.
116    
117    =back
118    
119  =cut  =cut
120    
121  # Declare the configuration variables.  # Declare the configuration variables.
122    
123  my $Destination = "NONE";       # Description of where to send the trace output.  my $Destination = "NONE";       # Description of where to send the trace output.
124    my $TeeFlag = 0;            # TRUE if output is going to a file and to the
125                                # standard output
126  my %Categories = ( main => 1 );  my %Categories = ( main => 1 );
127                                                          # hash of active category names                                                          # hash of active category names
128  my $TraceLevel = 0;                     # trace level; a higher trace level produces more  my $TraceLevel = 0;                     # trace level; a higher trace level produces more
129                                                          # messages                                                          # messages
130  my @Queue = ();                         # queued list of trace messages.  my @Queue = ();                         # queued list of trace messages.
131    my $LastCategory = "main";  # name of the last category interrogated
132    my $SetupCount = 0;         # number of times TSetup called
133    my $AllTrace = 0;           # TRUE if we are tracing all categories.
134    
135  =head2 Public Methods  =head2 Public Methods
136    
# Line 90  Line 152 
152    
153  The destination for the trace output. To send the trace output to a file, specify the file  The destination for the trace output. To send the trace output to a file, specify the file
154  name preceded by a ">" symbol. If a double symbol is used (">>"), then the data is appended  name preceded by a ">" symbol. If a double symbol is used (">>"), then the data is appended
155  to the file. Otherwise the file is cleared before tracing begins. In addition to sending  to the file. Otherwise the file is cleared before tracing begins. Precede the first ">"
156  the trace messages to a file, you can specify a special destination. C<HTML> will cause  symbol with a C<+> to echo output to a file AND to the standard output. In addition to
157  tracing to the standard output with each line formatted as an HTML paragraph. C<TEXT>  sending the trace messages to a file, you can specify a special destination. C<HTML> will
158    cause tracing to the standard output with each line formatted as an HTML paragraph. C<TEXT>
159  will cause tracing to the standard output as ordinary text. C<ERROR> will cause trace  will cause tracing to the standard output as ordinary text. C<ERROR> will cause trace
160  messages to be sent to the standard error output as ordinary text. C<QUEUE> will cause trace  messages to be sent to the standard error output as ordinary text. C<QUEUE> will cause trace
161  messages to be stored in a queue for later retrieval by the L</QTrace> method. C<WARN> will  messages to be stored in a queue for later retrieval by the L</QTrace> method. C<WARN> will
# Line 110  Line 173 
173          my @categoryData = split /\s+/, $categoryList;          my @categoryData = split /\s+/, $categoryList;
174          # Extract the trace level.          # Extract the trace level.
175          $TraceLevel = shift @categoryData;          $TraceLevel = shift @categoryData;
176          # Build the category hash.      # Presume category-based tracing until we learn otherwise.
177        $AllTrace = 0;
178        # Build the category hash. Note that if we find a "*", we turn on non-category
179        # tracing. We must also clear away any pre-existing data.
180        %Categories = ( main => 1 );
181          for my $category (@categoryData) {          for my $category (@categoryData) {
182                  $Categories{$category} = 1;          if ($category eq '*') {
183                $AllTrace = 1;
184            } else {
185                $Categories{lc $category} = 1;
186            }
187          }          }
188          # Now we need to process the destination information. The most important special          # Now we need to process the destination information. The most important special
189          # case is the single ">", which requires we clear the file first. After doing      # cases are the single ">", which requires we clear the file first, and the
190          # so, we tack on another ">" sign so that future trace messages are appended.      # "+" prefix which indicates a double echo.
191        if ($target =~ m/^\+?>>?/) {
192            if ($target =~ m/^\+/) {
193                $TeeFlag = 1;
194                $target = substr($target, 1);
195            }
196          if ($target =~ m/^>[^>]/) {          if ($target =~ m/^>[^>]/) {
197                  open TRACEFILE, $target;                  open TRACEFILE, $target;
198                  print TRACEFILE Now() . " Tracing initialized.\n";                  print TRACEFILE Now() . " Tracing initialized.\n";
199                  close TRACEFILE;                  close TRACEFILE;
200                  $Destination = ">$target";                  $Destination = ">$target";
201          } else {          } else {
202                $Destination = $target;
203            }
204        } else {
205                  $Destination = uc($target);                  $Destination = uc($target);
206          }          }
207        # Increment the setup counter.
208        $SetupCount++;
209    }
210    
211    =head3 StandardSetup
212    
213    C<< my ($options, @parameters) = StandardSetup(\@categories, \%options, $parmHelp, @ARGV); >>
214    
215    This method performs standard command-line parsing and tracing setup. The return
216    values are a hash of the command-line options and a list of the positional
217    parameters. Tracing is automatically set up and the command-line options are
218    validated.
219    
220    This is a complex method that does a lot of grunt work. The parameters can
221    be more easily understood, however, once they are examined individually.
222    
223    The I<categories> parameter is the most obtuse. It is a reference to a list of
224    special-purpose tracing categories. Most tracing categories are PERL package
225    names. So, for example, if you wanted to turn on tracing inside the B<Sprout>,
226    B<ERDB>, and B<SproutLoad> packages, you would specify the categories
227    
228        ["Sprout", "SproutLoad", "ERDB"]
229    
230    This would cause trace messages in the specified three packages to appear in
231    the output. There are threer special tracing categories that are automatically
232    handled by this method. In other words, if you used L</TSetup> you would need
233    to include these categories manually, but if you use this method they are turned
234    on automatically.
235    
236    =over 4
237    
238    =item FIG
239    
240    Turns on trace messages inside the B<FIG> package.
241    
242    =item SQL
243    
244    Traces SQL commands and activity.
245    
246    =item Tracer
247    
248    Traces error messages and call stacks.
249    
250    =back
251    
252    C<SQL> is only turned on if the C<-sql> option is specified in the command line.
253    The trace level is specified using the C<-trace> command-line option. For example,
254    the following command line for C<TransactFeatures> turns on SQL tracing and runs
255    all tracing at level 3.
256    
257        TransactFeatures -trace=3 -sql register ../xacts IDs.tbl
258    
259    Standard tracing is output to the standard output and echoed to the file
260    C<trace>I<$$>C<.log> in the FIG temporary directory, where I<$$> is the
261    process ID. You can also specify the C<user> parameter to put a user ID
262    instead of a process ID in the trace file name. So, for example
263    
264    The default trace level is 2. To get all messages, specify a trace level of 4.
265    For a genome-by-genome update, use 3.
266    
267        TransactFeatures -trace=3 -sql -user=Bruce register ../xacts IDs.tbl
268    
269    would send the trace output to C<traceBruce.log> in the temporary directory.
270    
271    The I<options> parameter is a reference to a hash containing the command-line
272    options, their default values, and an explanation of what they mean. Command-line
273    options may be in the form of switches or keywords. In the case of a switch, the
274    option value is 1 if it is specified and 0 if it is not specified. In the case
275    of a keyword, the value is separated from the option name by an equal sign. You
276    can see this last in the command-line example above.
277    
278    An example at this point would help. Consider, for example, the command-line utility
279    C<TransactFeatures>. It accepts a list of positional parameters plus the options
280    C<safe>, C<noAlias>, C<start>, and C<tblFiles>. To start up this command, we execute
281    the following code.
282    
283        my ($options, @parameters) = Tracer::StandardSetup(["DocUtils"],
284                            { safe => [0, "use database transactions"],
285                              noAlias => [0, "do not expect aliases in CHANGE transactions"],
286                              start => [' ', "start with this genome"],
287                              tblFiles => [0, "output TBL files containing the corrected IDs"] },
288                            "command transactionDirectory IDfile",
289                          @ARGV);
290    
291    
292    The call to C<ParseCommand> specifies the default values for the options and
293    stores the actual options in a hash that is returned as C<$options>. The
294    positional parameters are returned in C<@parameters>.
295    
296    The following is a sample command line for C<TransactFeatures>.
297    
298        TransactFeatures -trace=2 -noAlias register ../xacts IDs.tbl
299    
300    In this case, C<register>, C<../xacts>, and C<IDs.tbl> are the positional
301    parameters, and would find themselves in I<@parameters> after executing the
302    above code fragment. The tracing would be set to level 2, and the categories
303    would be C<FIG>, C<Tracer>, and <DocUtils>. C<FIG> and C<Tracer> are standard,
304    and C<DocUtils> was included because it came in within the first parameter
305    to this method. The I<$options> hash would be
306    
307        { trace => 2, sql => 0, safe => 0,
308          noAlias => 1, start => ' ', tblFiles => 0 }
309    
310    Use of C<StandardSetup> in this way provides a simple way of performing
311    standard tracing setup and command-line parsing. Note that the caller is
312    not even aware of the command-line switches C<-trace> and C<-sql>, which
313    are used by this method to control the tracing. If additional tracing features
314    need to be added in the future, they can be processed by this method without
315    upsetting the command-line utilities.
316    
317    Finally, if the special option C<-h> is specified, the option names will
318    be traced at level 0 and the program will exit without processing.
319    This provides a limited help capability. For example, if the user enters
320    
321        TransactFeatures -h
322    
323    he would see the following output.
324    
325        TransactFeatures [options] command transactionDirectory IDfile
326            -trace    tracing level (default 2)
327            -sql      trace SQL commands
328            -safe     use database transactions
329            -noAlias  do not expect aliases in CHANGE transactions
330            -start    start with this genome
331            -tblFiles output TBL files containing the corrected IDs
332    
333    The parameters to this method are as follows.
334    
335    =over 4
336    
337    =item categories
338    
339    Reference to a list of tracing category names. These should be names of
340    packages whose internal workings will need to be debugged to get the
341    command working.
342    
343    =item options
344    
345    Reference to a hash containing the legal options for the current command mapped
346    to their default values and descriptions. The user can override the defaults
347    by specifying the options as command-line switches prefixed by a hyphen.
348    Tracing-related options may be added to this hash. If the C<-h> option is
349    specified on the command line, the option descriptions will be used to
350    explain the options.
351    
352    =item parmHelp
353    
354    A string that vaguely describes the positional parameters. This is used
355    if the user specifies the C<-h> option.
356    
357    =item ARGV
358    
359    List of command line parameters, including the option switches, which must
360    precede the positional parameters and be prefixed by a hyphen.
361    
362    =item RETURN
363    
364    Returns a list. The first element of the list is the reference to a hash that
365    maps the command-line option switches to their values. These will either be the
366    default values or overrides specified on the command line. The remaining
367    elements of the list are the position parameters, in order.
368    
369    =back
370    
371    =cut
372    
373    sub StandardSetup {
374        # Get the parameters.
375        my ($categories, $options, $parmHelp, @argv) = @_;
376        # Add the tracing options.
377        if (! exists $options->{trace}) {
378            $options->{trace} = [2, "tracing level"];
379        }
380        $options->{sql} = [0, "turn on SQL tracing"];
381        $options->{h} = [0, "display command-line options"];
382        $options->{user} = [$$, "trace log file name suffix"];
383        # Create a parsing hash from the options hash. The parsing hash
384        # contains the default values rather than the default value
385        # and the description. While we're at it, we'll memorize the
386        # length of the longest option name.
387        my $longestName = 0;
388        my %parseOptions = ();
389        for my $key (keys %{$options}) {
390            if (length $key > $longestName) {
391                $longestName = length $key;
392            }
393            $parseOptions{$key} = $options->{$key}->[0];
394        }
395        # Parse the command line.
396        my ($retOptions, @retParameters) = ParseCommand(\%parseOptions, @argv);
397        # Now we want to set up tracing. First, we need to know if SQL is to
398        # be traced.
399        my @cats = @{$categories};
400        if ($retOptions->{sql}) {
401            push @cats, "SQL";
402        }
403        # Add the default categories.
404        push @cats, "Tracer", "FIG";
405        # Next, we create the category string by prefixing the trace level
406        # and joining the categories.
407        my $cats = join(" ", $parseOptions{trace}, @cats);
408        # Verify that we can open a file in the temporary directory.
409        my $traceMode = "TEXT";
410        my $suffix = $retOptions->{user};
411        my $traceFileName = "$FIG_Config::temp/trace$suffix.log";
412        if (open TESTTRACE, ">$traceFileName") {
413            $traceMode = "+>$traceFileName";
414            close TESTTRACE;
415        }
416        # Now set up the tracing.
417        TSetup($cats, $traceMode);
418        # Check for the "h" option. If it is specified, dump the command-line
419        # options and exit the program.
420        if ($retOptions->{h}) {
421            $0 =~ m#[/\\](\w+)(\.pl)?$#i;
422            Trace("$1 [options] $parmHelp") if T(0);
423            for my $key (sort keys %{$options}) {
424                my $name = Pad($key, $longestName, 0, ' ');
425                my $desc = $options->{$key}->[1];
426                if ($options->{$key}->[0]) {
427                    $desc .= " (default " . $options->{$key}->[0] . ")";
428                }
429                Trace("  $name $desc") if T(0);
430            }
431            exit(0);
432        }
433        # Return the parsed parameters.
434        return ($retOptions, @retParameters);
435    }
436    
437    =head3 Setups
438    
439    C<< my $count = Tracer::Setups(); >>
440    
441    Return the number of times L</TSetup> has been called.
442    
443    This method allows for the creation of conditional tracing setups where, for example, we
444    may want to set up tracing if nobody else has done it before us.
445    
446    =cut
447    
448    sub Setups {
449        return $SetupCount;
450    }
451    
452    =head3 Open
453    
454    C<< my $handle = Open($fileHandle, $fileSpec, $message); >>
455    
456    Open a file.
457    
458    The I<$fileSpec> is essentially the second argument of the PERL C<open>
459    function. The mode is specified using Unix-like shell information. So, for
460    example,
461    
462        Open(\*LOGFILE, '>>/usr/spool/news/twitlog', "Could not open twit log.");
463    
464    would open for output appended to the specified file, and
465    
466        Open(\*DATASTREAM, "| sort -u >$outputFile", "Could not open $outputFile.");
467    
468    would open a pipe that sorts the records written and removes duplicates. Note
469    the use of file handle syntax in the Open call. To use anonymous file handles,
470    code as follows.
471    
472        my $logFile = Open(undef, '>>/usr/spool/news/twitlog', "Could not open twit log.");
473    
474    The I<$message> parameter is used if the open fails. If it is set to C<0>, then
475    the open returns TRUE if successful and FALSE if an error occurred. Otherwise, a
476    failed open will throw an exception and the third parameter will be used to construct
477    an error message. If the parameter is omitted, a standard message is constructed
478    using the file spec.
479    
480        Could not open "/usr/spool/news/twitlog"
481    
482    Note that the mode characters are automatically cleaned from the file name.
483    The actual error message from the file system will be captured and appended to the
484    message in any case.
485    
486        Could not open "/usr/spool/news/twitlog": file not found.
487    
488    In some versions of PERL the only error message we get is a number, which
489    corresponds to the C++ C<errno> value.
490    
491        Could not open "/usr/spool/news/twitlog": 6.
492    
493    =over 4
494    
495    =item fileHandle
496    
497    File handle. If this parameter is C<undef>, a file handle will be generated
498    and returned as the value of this method.
499    
500    =item fileSpec
501    
502    File name and mode, as per the PERL C<open> function.
503    
504    =item message (optional)
505    
506    Error message to use if the open fails. If omitted, a standard error message
507    will be generated. In either case, the error information from the file system
508    is appended to the message. To specify a conditional open that does not throw
509    an error if it fails, use C<0>.
510    
511    =item RETURN
512    
513    Returns the name of the file handle assigned to the file, or C<undef> if the
514    open failed.
515    
516    =back
517    
518    =cut
519    
520    sub Open {
521        # Get the parameters.
522        my ($fileHandle, $fileSpec, $message) = @_;
523        # Attempt to open the file.
524        my $rv = open $fileHandle, $fileSpec;
525        # If the open failed, generate an error message.
526        if (! $rv) {
527            # Save the system error message.
528            my $sysMessage = $!;
529            # See if we need a default message.
530            if (!$message) {
531                # Clean any obvious mode characters and leading spaces from the
532                # filename.
533                my ($fileName) = FindNamePart($fileSpec);
534                $message = "Could not open \"$fileName\"";
535            }
536            # Terminate with an error using the supplied message and the
537            # error message from the file system.
538            Confess("$message: $!");
539        }
540        # Return the file handle.
541        return $fileHandle;
542    }
543    
544    =head3 FindNamePart
545    
546    C<< my ($fileName, $start, $len) = Tracer::FindNamePart($fileSpec); >>
547    
548    Extract the portion of a file specification that contains the file name.
549    
550    A file specification is the string passed to an C<open> call. It specifies the file
551    mode and name. In a truly complex situation, it can specify a pipe sequence. This
552    method assumes that the file name is whatever follows the first angle bracket
553    sequence.  So, for example, in the following strings the file name is
554    C</usr/fig/myfile.txt>.
555    
556        >>/usr/fig/myfile.txt
557        </usr/fig/myfile.txt
558        | sort -u > /usr/fig/myfile.txt
559    
560    If the method cannot find a file name using its normal methods, it will return the
561    whole incoming string.
562    
563    =over 4
564    
565    =item fileSpec
566    
567    File specification string from which the file name is to be extracted.
568    
569    =item RETURN
570    
571    Returns a three-element list. The first element contains the file name portion of
572    the specified string, or the whole string if a file name cannot be found via normal
573    methods. The second element contains the start position of the file name portion and
574    the third element contains the length.
575    
576    =back
577    
578    =cut
579    #: Return Type $;
580    sub FindNamePart {
581        # Get the parameters.
582        my ($fileSpec) = @_;
583        # Default to the whole input string.
584        my ($retVal, $pos, $len) = ($fileSpec, 0, length $fileSpec);
585        # Parse out the file name if we can.
586        if ($fileSpec =~ m/(<|>>?)(.+?)(\s*)$/) {
587            $retVal = $2;
588            $len = length $retVal;
589            $pos = (length $fileSpec) - (length $3) - $len;
590        }
591        # Return the result.
592        return ($retVal, $pos, $len);
593    }
594    
595    =head3 OpenDir
596    
597    C<< my @files = OpenDir($dirName, $filtered, $flag); >>
598    
599    Open a directory and return all the file names. This function essentially performs
600    the functions of an C<opendir> and C<readdir>. If the I<$filtered> parameter is
601    set to TRUE, all filenames beginning with a period (C<.>), dollar sign (C<$>),
602    or pound sign (C<#>) and all filenames ending with a tilde C<~>) will be
603    filtered out of the return list. If the directory does not open and I<$flag> is not
604    set, an exception is thrown. So, for example,
605    
606        my @files = OpenDir("/Volumes/fig/contigs", 1);
607    
608    is effectively the same as
609    
610        opendir(TMP, "/Volumes/fig/contigs") || Confess("Could not open /Volumes/fig/contigs.");
611        my @files = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir(TMP);
612    
613    Similarly, the following code
614    
615        my @files = grep { $_ =~ /^\d/ } OpenDir("/Volumes/fig/orgs", 0, 1);
616    
617    Returns the names of all files in C</Volumes/fig/orgs> that begin with digits and
618    automatically returns an empty list if the directory fails to open.
619    
620    =over 4
621    
622    =item dirName
623    
624    Name of the directory to open.
625    
626    =item filtered
627    
628    TRUE if files whose names begin with a period (C<.>) should be automatically removed
629    from the list, else FALSE.
630    
631    =item flag
632    
633    TRUE if a failure to open is okay, else FALSE
634    
635    =back
636    
637    =cut
638    #: Return Type @;
639    sub OpenDir {
640        # Get the parameters.
641        my ($dirName, $filtered, $flag) = @_;
642        # Declare the return variable.
643        my @retVal = ();
644        # Open the directory.
645        if (opendir(my $dirHandle, $dirName)) {
646            # The directory opened successfully. Get the appropriate list according to the
647            # strictures of the filter parameter.
648            if ($filtered) {
649                @retVal = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir $dirHandle;
650            } else {
651                @retVal = readdir $dirHandle;
652            }
653        } elsif (! $flag) {
654            # Here the directory would not open and it's considered an error.
655            Confess("Could not open directory $dirName.");
656        }
657        # Return the result.
658        return @retVal;
659  }  }
660    
661  =head3 SetLevel  =head3 SetLevel
# Line 370  Line 901 
901          my ($message) = @_;          my ($message) = @_;
902          # Get the timestamp.          # Get the timestamp.
903          my $timeStamp = Now();          my $timeStamp = Now();
904          # Format the message.      # Format the message. Note we strip off any line terminators at the end.
905          my $formatted = "$timeStamp $message";      my $formatted = "$timeStamp <$LastCategory>: " . Strip($message);
906          # Process according to the destination.          # Process according to the destination.
907          if ($Destination eq "TEXT") {          if ($Destination eq "TEXT") {
908                  # Write the message to the standard output.                  # Write the message to the standard output.
# Line 391  Line 922 
922         warn $message;         warn $message;
923          } elsif ($Destination =~ m/^>>/) {          } elsif ($Destination =~ m/^>>/) {
924                  # Write the trace message to an output file.                  # Write the trace message to an output file.
925                  open TRACING, $Destination;          (open TRACING, $Destination) || die "Tracing open for \"$Destination\" failed: $!";
926                  print TRACING "$formatted\n";                  print TRACING "$formatted\n";
927                  close TRACING;                  close TRACING;
928            # If the Tee flag is on, echo it to the standard output.
929            if ($TeeFlag) {
930                print "$formatted\n";
931            }
932          }          }
933  }  }
934    
# Line 436  Line 971 
971                  my ($category, $traceLevel) = @_;                  my ($category, $traceLevel) = @_;
972                  if (!defined $traceLevel) {                  if (!defined $traceLevel) {
973                          # Here we have no category, so we need to get the calling package.                          # Here we have no category, so we need to get the calling package.
974                # The calling package is normally the first parameter. If it is
975                # omitted, the first parameter will be the tracelevel. So, the
976                # first thing we do is shift the so-called category into the
977                # $traceLevel variable where it belongs.
978                          $traceLevel = $category;                          $traceLevel = $category;
979                          my ($package, $fileName, $line) = caller;                          my ($package, $fileName, $line) = caller;
980              # If there is no calling package, we default to "main".              # If there is no calling package, we default to "main".
# Line 445  Line 984 
984                                  $category = $package;                                  $category = $package;
985                          }                          }
986                  }                  }
987                  # Use the package and tracelevel to compute the result.          # Save the category name.
988                  $retVal = ($traceLevel <= $TraceLevel && exists $Categories{$category});          $LastCategory = $category;
989            # Convert it to lower case before we hash it.
990            $category = lc $category;
991            # Use the category and tracelevel to compute the result.
992            if (ref $traceLevel) {
993                Confess("Bad trace level.");
994            } elsif (ref $TraceLevel) {
995                Confess("Bad trace config.");
996            }
997            $retVal = ($traceLevel <= $TraceLevel && ($AllTrace || exists $Categories{$category}));
998      }      }
999          # Return the computed result.          # Return the computed result.
1000      return $retVal;      return $retVal;
# Line 528  Line 1076 
1076          return ($optionTable, @retVal);          return ($optionTable, @retVal);
1077  }  }
1078    
1079    =head3 Escape
1080    
1081    C<< my $codedString = Tracer::Escape($realString); >>
1082    
1083    Escape a string for use in a command length. Tabs will be replaced by C<\t>, new-lines
1084    replaced by C<\n>, carriage returns will be deleted, and backslashes will be doubled. The
1085    result is to reverse the effect of L</UnEscape>.
1086    
1087    =over 4
1088    
1089    =item realString
1090    
1091    String to escape.
1092    
1093    =item RETURN
1094    
1095    Escaped equivalent of the real string.
1096    
1097    =back
1098    
1099    =cut
1100    
1101    sub Escape {
1102        # Get the parameter.
1103        my ($realString) = @_;
1104        # Initialize the return variable.
1105        my $retVal = "";
1106        # Loop through the parameter string, looking for sequences to escape.
1107        while (length $realString > 0) {
1108            # Look for the first sequence to escape.
1109            if ($realString =~ /^(.*?)([\n\t\r\\])/) {
1110                # Here we found it. The text preceding the sequence is in $1. The sequence
1111                # itself is in $2. First, move the clear text to the return variable.
1112                $retVal .= $1;
1113                # Strip the processed section off the real string.
1114                $realString = substr $realString, (length $2) + (length $1);
1115                # Get the matched character.
1116                my $char = $2;
1117                # If we have a CR, we are done.
1118                if ($char ne "\r") {
1119                    # It's not a CR, so encode the escape sequence.
1120                    $char =~ tr/\t\n/tn/;
1121                    $retVal .= "\\" . $char;
1122                }
1123            } else {
1124                # Here there are no more escape sequences. The rest of the string is
1125                # transferred unmodified.
1126                $retVal .= $realString;
1127                $realString = "";
1128            }
1129        }
1130        # Return the result.
1131        return $retVal;
1132    }
1133    
1134  =head3 UnEscape  =head3 UnEscape
1135    
1136  C<< my $realString = Tracer::UnEscape($codedString); >>  C<< my $realString = Tracer::UnEscape($codedString); >>
1137    
1138  Replace escape sequences with their actual equivalents. C<\b> will be replaced by a space,  Replace escape sequences with their actual equivalents. C<\t> will be replaced by
1139  C<\t> by a tab, C<\n> by a new-line character, and C<\\> by a back-slash.  a tab, C<\n> by a new-line character, and C<\\> by a backslash. C<\r> codes will
1140    be deleted.
1141    
1142  =over 4  =over 4
1143    
# Line 555  Line 1159 
1159          my ($codedString) = @_;          my ($codedString) = @_;
1160          # Initialize the return variable.          # Initialize the return variable.
1161          my $retVal = "";          my $retVal = "";
1162        # Only proceed if the incoming string is nonempty.
1163        if (defined $codedString) {
1164          # Loop through the parameter string, looking for escape sequences. We can't do          # Loop through the parameter string, looking for escape sequences. We can't do
1165          # translating because it causes problems with the escaped slash. ("\\b" becomes          # translating because it causes problems with the escaped slash. ("\\t" becomes
1166          # "\ " no matter what we do.)          # "\<tab>" no matter what we do.)
1167          while (length $codedString > 0) {          while (length $codedString > 0) {
1168                  # Look for the first escape sequence.                  # Look for the first escape sequence.
1169                  if ($codedString =~ /^(.*?)\\(\\|b|n|t)/) {              if ($codedString =~ /^(.*?)\\(\\|n|t|r)/) {
1170                          # Here we found it. The text preceding the sequence is in $1. The sequence                          # Here we found it. The text preceding the sequence is in $1. The sequence
1171                          # itself is in $2. First, move the clear text to the return variable.                          # itself is in $2. First, move the clear text to the return variable.
1172                          $retVal .= $1;                          $retVal .= $1;
1173                          $codedString = substr $codedString, (2 + length $1);                          $codedString = substr $codedString, (2 + length $1);
1174                          # Decode the escape sequence.                  # Get the escape value.
1175                          my $char = $2;                          my $char = $2;
1176                          $char =~ tr/\\btn/\\ \t\n/;                  # If we have a "\r", we are done.
1177                    if ($char ne 'r') {
1178                        # Here it's not an 'r', so we convert it.
1179                        $char =~ tr/\\tn/\\\t\n/;
1180                          $retVal .= $char;                          $retVal .= $char;
1181                    }
1182                  } else {                  } else {
1183                          # Here there are no more escape sequences. The rest of the string is                          # Here there are no more escape sequences. The rest of the string is
1184                          # transferred unmodified.                          # transferred unmodified.
# Line 576  Line 1186 
1186                          $codedString = "";                          $codedString = "";
1187                  }                  }
1188          }          }
1189        }
1190          # Return the result.          # Return the result.
1191          return $retVal;          return $retVal;
1192  }  }
# Line 677  Line 1288 
1288    
1289  C<< my @fileContents = Tracer::GetFile($fileName); >>  C<< my @fileContents = Tracer::GetFile($fileName); >>
1290    
1291  Return the entire contents of a file.      or
1292    
1293    C<< my $fileContents = Tracer::GetFile($fileName); >>
1294    
1295    Return the entire contents of a file. In list context, line-ends are removed and
1296    each line is a list element. In scalar context, line-ends are replaced by C<\n>.
1297    
1298  =over 4  =over 4
1299    
# Line 688  Line 1304 
1304  =item RETURN  =item RETURN
1305    
1306  In a list context, returns the entire file as a list with the line terminators removed.  In a list context, returns the entire file as a list with the line terminators removed.
1307  In a scalar context, returns the entire file as a string.  In a scalar context, returns the entire file as a string. If an error occurs opening
1308    the file, an empty list will be returned.
1309    
1310  =back  =back
1311    
# Line 703  Line 1320 
1320          my $ok = open INPUTFILE, "<$fileName";          my $ok = open INPUTFILE, "<$fileName";
1321          if (!$ok) {          if (!$ok) {
1322                  # If we had an error, trace it. We will automatically return a null value.                  # If we had an error, trace it. We will automatically return a null value.
1323                  Trace("Could not open \"$fileName\" for input.") if T(0);          Trace("Could not open \"$fileName\" for input: $!") if T(0);
1324          } else {          } else {
1325                  # Read the whole file into the return variable, stripping off an terminator          # Read the whole file into the return variable, stripping off any terminator
1326          # characters.          # characters.
1327          my $lineCount = 0;          my $lineCount = 0;
1328                  while (my $line = <INPUTFILE>) {                  while (my $line = <INPUTFILE>) {
1329              $lineCount++;              $lineCount++;
1330              $line =~ s/(\r|\n)+$//g;              $line = Strip($line);
1331                          push @retVal, $line;                          push @retVal, $line;
1332                  }                  }
1333                  # Close it.                  # Close it.
1334                  close INPUTFILE;                  close INPUTFILE;
1335          my $actualLines = @retVal;          my $actualLines = @retVal;
         Trace("$lineCount lines read from $fileName. $actualLines processed.") if T(0);  
1336          }          }
1337          # Return the file's contents in the desired format.          # Return the file's contents in the desired format.
1338      if (wantarray) {      if (wantarray) {
# Line 747  Line 1363 
1363          my ($format) = @_;          my ($format) = @_;
1364          # Create the return variable.          # Create the return variable.
1365          my $retVal = "";          my $retVal = "";
1366        # Only proceed if there is an actual queue.
1367        if (@Queue) {
1368          # Process according to the format.          # Process according to the format.
1369          if ($format =~ m/^HTML$/i) {          if ($format =~ m/^HTML$/i) {
1370                  # Convert the queue into an HTML list.                  # Convert the queue into an HTML list.
# Line 762  Line 1380 
1380          }          }
1381          # Clear the queue.          # Clear the queue.
1382          @Queue = ();          @Queue = ();
1383        }
1384          # Return the formatted list.          # Return the formatted list.
1385          return $retVal;          return $retVal;
1386  }  }
# Line 770  Line 1389 
1389    
1390  C<< Confess($message); >>  C<< Confess($message); >>
1391    
1392  Trace the call stack and abort the program with the specified message. The stack  Trace the call stack and abort the program with the specified message. When used with
 trace will only appear if the trace level for this package is 1 or more. When used with  
1393  the OR operator and the L</Assert> method, B<Confess> can function as a debugging assert.  the OR operator and the L</Assert> method, B<Confess> can function as a debugging assert.
1394  So, for example  So, for example
1395    
# Line 793  Line 1411 
1411          # Get the parameters.          # Get the parameters.
1412          my ($message) = @_;          my ($message) = @_;
1413          # Trace the call stack.          # Trace the call stack.
1414          Cluck($message) if T(1);      Cluck($message);
1415          # Abort the program.          # Abort the program.
1416          croak(">>> $message");          croak(">>> $message");
1417  }  }
# Line 803  Line 1421 
1421  C<< Assert($condition1, $condition2, ... $conditionN); >>  C<< Assert($condition1, $condition2, ... $conditionN); >>
1422    
1423  Return TRUE if all the conditions are true. This method can be used in conjunction with  Return TRUE if all the conditions are true. This method can be used in conjunction with
1424  the OR operator and the L</Confess> method, B<Assert> can function as a debugging assert.  the OR operator and the L</Confess> method as a debugging assert.
1425  So, for example  So, for example
1426    
1427  C<< Assert($recNum >= 0) || Confess("Invalid record number $recNum."); >>  C<< Assert($recNum >= 0) || Confess("Invalid record number $recNum."); >>
# Line 958  Line 1576 
1576      }      }
1577  }  }
1578    
1579    =head3 DebugMode
1580    
1581    C<< if (Tracer::DebugMode) { ...code... } >>
1582    
1583    Return TRUE if debug mode has been turned on, else output an error
1584    page and return FALSE.
1585    
1586    Certain CGI scripts are too dangerous to exist in the production
1587    environment. This method provides a simple way to prevent them
1588    from working unless they are explicitly turned on by creating a password
1589    cookie via the B<SetPassword> script.  If debugging mode
1590    is not turned on, an error web page will be output directing the
1591    user to enter in the correct password.
1592    
1593    =cut
1594    
1595    sub DebugMode {
1596        # Declare the return variable.
1597        my $retVal = 0;
1598        # Check the debug configuration.
1599        my $password = CGI::cookie("DebugMode");
1600        my $encrypted = Digest::MD5::md5_hex($password);
1601        if ($encrypted eq "252dec43280e0c0d6a75ffcec486e61d") {
1602            $retVal = 1;
1603        } else {
1604            # Here debug mode is off, so we generate an error page.
1605            my $pageString = PageBuilder::Build("<Html/ErrorPage.html", {}, "Html");
1606            print $pageString;
1607        }
1608        # Return the determination indicator.
1609        return $retVal;
1610    }
1611    
1612    =head3 Strip
1613    
1614    C<< my $string = Tracer::Strip($line); >>
1615    
1616    Strip all line terminators off a string. This is necessary when dealing with files
1617    that may have been transferred back and forth several times among different
1618    operating environments.
1619    
1620    =over 4
1621    
1622    =item line
1623    
1624    Line of text to be stripped.
1625    
1626    =item RETURN
1627    
1628    The same line of text with all the line-ending characters chopped from the end.
1629    
1630    =back
1631    
1632    =cut
1633    
1634    sub Strip {
1635        # Get a copy of the parameter string.
1636        my ($string) = @_;
1637        my $retVal = (defined $string ? $string : "");
1638        # Strip the line terminator characters.
1639        $retVal =~ s/(\r|\n)+$//g;
1640        # Return the result.
1641        return $retVal;
1642    }
1643    
1644    =head3 Pad
1645    
1646    C<< my $paddedString = Tracer::Pad($string, $len, $left, $padChar); >>
1647    
1648    Pad a string to a specified length. The pad character will be a
1649    space, and the padding will be on the right side unless specified
1650    in the third parameter.
1651    
1652    =over 4
1653    
1654    =item string
1655    
1656    String to be padded.
1657    
1658    =item len
1659    
1660    Desired length of the padded string.
1661    
1662    =item left (optional)
1663    
1664    TRUE if the string is to be left-padded; otherwise it will be padded on the right.
1665    
1666    =item padChar (optional)
1667    
1668    Character to use for padding. The default is a space.
1669    
1670    =item RETURN
1671    
1672    Returns a copy of the original string with the pad character added to the
1673    specified end so that it achieves the desired length.
1674    
1675    =back
1676    
1677    =cut
1678    
1679    sub Pad {
1680        # Get the parameters.
1681        my ($string, $len, $left, $padChar) = @_;
1682        # Compute the padding character.
1683        if (! defined $padChar) {
1684            $padChar = " ";
1685        }
1686        # Compute the number of spaces needed.
1687        my $needed = $len - length $string;
1688        # Copy the string into the return variable.
1689        my $retVal = $string;
1690        # Only proceed if padding is needed.
1691        if ($needed > 0) {
1692            # Create the pad string.
1693            my $pad = $padChar x $needed;
1694            # Affix it to the return value.
1695            if ($left) {
1696                $retVal = $pad . $retVal;
1697            } else {
1698                $retVal .= $pad;
1699            }
1700        }
1701        # Return the result.
1702        return $retVal;
1703    }
1704    
1705    =head3 EOF
1706    
1707    This is a constant that is lexically greater than any useful string.
1708    
1709    =cut
1710    
1711    sub EOF {
1712        return "\xFF\xFF\xFF\xFF\xFF";
1713    }
1714    
1715    =head3 TICK
1716    
1717    C<< my @results = TICK($commandString); >>
1718    
1719    Perform a back-tick operation on a command. If this is a Windows environment, any leading
1720    dot-slash (C<./> will be removed. So, for example, if you were doing
1721    
1722        `./protein.cgi`
1723    
1724    from inside a CGI script, it would work fine in Unix, but would issue an error message
1725    in Windows complaining that C<'.'> is not a valid command. If instead you code
1726    
1727        TICK("./protein.cgi")
1728    
1729    it will work correctly in both environments.
1730    
1731    =over 4
1732    
1733    =item commandString
1734    
1735    The command string to pass to the system.
1736    
1737    =item RETURN
1738    
1739    Returns the standard output from the specified command, as a list.
1740    
1741    =back
1742    
1743    =cut
1744    #: Return Type @;
1745    sub TICK {
1746        # Get the parameters.
1747        my ($commandString) = @_;
1748        # Chop off the dot-slash if this is Windows.
1749        if ($FIG_Config::win_mode) {
1750            $commandString =~ s!^\./!!;
1751        }
1752        # Activate the command and return the result.
1753        return `$commandString`;
1754    }
1755    
1756    =head3 ScriptSetup
1757    
1758    C<< my ($query, $varHash) = ScriptSetup(); >>
1759    
1760    Perform standard tracing and debugging setup for scripts. The value returned is
1761    the CGI object followed by a pre-built variable hash.
1762    
1763    The C<Trace> query parameter is used to determine whether or not tracing is active and
1764    which trace modules (other than C<Tracer> and C<FIG>) should be turned on. Specifying
1765    the C<CGI> trace module will trace parameter and environment information. Parameters are
1766    traced at level 3 and environment variables at level 4. At the end of the script, the
1767    client should call L</ScriptFinish> to output the web page.
1768    
1769    =cut
1770    
1771    sub ScriptSetup {
1772        # Get the CGI query object.
1773        my $query = CGI->new();
1774        # Check for tracing. Set it up if the user asked for it.
1775        if ($query->param('Trace')) {
1776            # Set up tracing to be queued for display at the bottom of the web page.
1777            TSetup($query->param('Trace') . " FIG Tracer", "QUEUE");
1778            # Trace the parameter and environment data.
1779            if (T(CGI => 3)) {
1780                # Here we want to trace the parameter data.
1781                my @names = $query->param;
1782                for my $parmName (sort @names) {
1783                    # Note we skip "Trace", which is for our use only.
1784                    if ($parmName ne 'Trace') {
1785                        my @values = $query->param($parmName);
1786                        Trace("CGI: $parmName = " . join(", ", @values));
1787                    }
1788                }
1789            }
1790            if (T(CGI => 4)) {
1791                # Here we want the environment data too.
1792                for my $envName (sort keys %ENV) {
1793                    Trace("ENV: $envName = $ENV{$envName}");
1794                }
1795            }
1796        } else {
1797            # Here tracing is to be turned off. All we allow is errors traced into the
1798            # error log.
1799            TSetup("0", "WARN");
1800        }
1801        # Create the variable hash.
1802        my $varHash = { DebugData => '' };
1803        # If we're in DEBUG mode, set up the debug mode data for forms.
1804        if (Tracer::DebugMode) {
1805            $varHash->{DebugData} = GetFile("Html/DebugFragment.html");
1806        }
1807        # Return the query object and variable hash.
1808        return ($query, $varHash);
1809    }
1810    
1811    =head3 ScriptFinish
1812    
1813    C<< ScriptFinish($webData, $varHash); >>
1814    
1815    Output a web page at the end of a script. Either the string to be output or the
1816    name of a template file can be specified. If the second parameter is omitted,
1817    it is assumed we have a string to be output; otherwise, it is assumed we have the
1818    name of a template file. The template should have the variable C<DebugData>
1819    specified in any form that invokes a standard script. If debugging mode is turned
1820    on, a form field will be put in that allows the user to enter tracing data.
1821    Trace messages will be placed immediately before the terminal C<BODY> tag in
1822    the output, formatted as a list.
1823    
1824    A typical standard script would loook like the following.
1825    
1826        BEGIN {
1827            # Print the HTML header.
1828            print "CONTENT-TYPE: text/html\n\n";
1829        }
1830        use Tracer;
1831        use CGI;
1832        use FIG;
1833        # ... more uses ...
1834    
1835        my ($query, $varHash) = ScriptSetup();
1836        eval {
1837            # ... get data from $query, put it in $varHash ...
1838        };
1839        if ($@) {
1840            Trace("Script Error: $@") if T(0);
1841        }
1842        ScriptFinish("Html/MyTemplate.html", $varHash);
1843    
1844    The idea here is that even if the script fails, you'll see trace messages and
1845    useful output.
1846    
1847    =over 4
1848    
1849    =item webData
1850    
1851    A string containing either the full web page to be written to the output or the
1852    name of a template file from which the page is to be constructed. If the name
1853    of a template file is specified, then the second parameter must be present;
1854    otherwise, it must be absent.
1855    
1856    =item varHash (optional)
1857    
1858    If specified, then a reference to a hash mapping variable names for a template
1859    to their values. The template file will be read into memory, and variable markers
1860    will be replaced by data in this hash reference.
1861    
1862    =back
1863    
1864    =cut
1865    
1866    sub ScriptFinish {
1867        # Get the parameters.
1868        my ($webData, $varHash) = @_;
1869        # Check for a template file situation.
1870        my $outputString;
1871        if (defined $varHash) {
1872            # Here we have a template file. We need to apply the variables to the template.
1873            $outputString = PageBuilder::Build("<$webData", $varHash, "Html");
1874        } else {
1875            # Here the user gave us a raw string.
1876            $outputString = $webData;
1877        }
1878        # Check for trace messages.
1879        if ($Destination eq "QUEUE") {
1880            # We have trace messages, so we want to put them at the end of the body. This
1881            # is either at the end of the whole string or at the beginning of the BODY
1882            # end-tag.
1883            my $pos = length $outputString;
1884            if ($outputString =~ m#</body>#gi) {
1885                $pos = (pos $outputString) - 7;
1886            }
1887            substr $outputString, $pos, 0, QTrace('Html');
1888        }
1889        # Write the output string.
1890        print $outputString;
1891    }
1892    
1893    =head3 Insure
1894    
1895    C<< Insure($dirName); >>
1896    
1897    Insure a directory is present.
1898    
1899    =over 4
1900    
1901    =item dirName
1902    
1903    Name of the directory to check. If it does not exist, it will be created.
1904    
1905    =back
1906    
1907    =cut
1908    
1909    sub Insure {
1910        my ($dirName) = @_;
1911        if (! -d $dirName) {
1912            Trace("Creating $dirName directory.") if T(2);
1913            mkpath $dirName;
1914        }
1915    }
1916    
1917  1;  1;

Legend:
Removed from v.1.6  
changed lines
  Added in v.1.41

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3