Tracing and Debugging Helpers

Tracing

This package provides simple tracing for debugging and reporting purposes. To use it simply call the TSetup or ETracing method to set the options and call Trace to write out trace messages. TSetup and ETracing both establish a trace level and a list of categories. Similarly, each trace message has a trace level and category associated with it. Only messages whose trace level is less than or equal to the setup trace level and whose category is activated will be written. Thus, a higher trace level on a message indicates that the message is less likely to be seen, while a higher trace level passed to TSetup means more trace messages will appear.

Putting Trace Messages in Your Code

To generate a trace message, use the following syntax.

    Trace($message) if T(errors => 4);

This statement will produce a trace message if the trace level is 4 or more and the errors category is active. There is a special category main that is always active, so

    Trace($message) if T(main => 4);

will trace if the trace level is 4 or more.

If the category name is the same as the package name, all you need is the number. So, if the following call is made in the Sprout package, it will appear if the Sprout category is active and the trace level is 2 or more.

    Trace($message) if T(2);

In scripts, where no package name is available, the category defaults to main.

Custom Tracing

Many programs have customized tracing configured using the TSetup method. This is no longer the preferred method, but a knowledge of how custom tracing works can make the more modern Emergency Tracing easier to understand.

To set up custom tracing, you call the TSetup method. The method takes as input a trace level, a list of category names, and a destination. The trace level and list of category names are specified as a space-delimited string. Thus

    TSetup('3 errors Sprout ERDB', 'TEXT');

sets the trace level to 3, activates the errors, Sprout, and ERDB categories, and specifies that messages should be sent to the standard output.

To turn on tracing for ALL categories, use an asterisk. The call below sets every category to level 3 and writes the output to the standard error output. This sort of thing might be useful in a CGI environment.

    TSetup('3 *', 'WARN');

In addition standard error and file output for trace messages, you can specify that the trace messages be queued. The messages can then be retrieved by calling the QTrace method. This approach is useful if you are building a web page. Instead of having the trace messages interspersed with the page output, they can be gathered together and displayed at the end of the page. This makes it easier to debug page formatting problems.

Finally, you can specify that all trace messages be emitted to a file, or the standard output and a file at the same time. To trace to a file, specify the filename with an output character in front of it.

    TSetup('4 SQL', ">$fileName");

To trace to the standard output and a file at the same time, put a + in front of the angle bracket.

    TSetup('3 *', "+>$fileName");

The flexibility of tracing makes it superior to simple use of directives like die and warn. Tracer calls can be left in the code with minimal overhead and then turned on only when needed. Thus, debugging information is available and easily retrieved even when the application is being used out in the field.

Trace Levels

There is no hard and fast rule on how to use trace levels. The following is therefore only a suggestion.

Error 0
Message indicates an error that may lead to incorrect results or that has stopped the application entirely.

Warning 1
Message indicates something that is unexpected but that probably did not interfere with program execution.

Notice 2
Message indicates the beginning or end of a major task.

Information 3
Message indicates a subtask. In the FIG system, a subtask generally relates to a single genome. This would be a big loop that is not expected to execute more than 500 times or so.

Detail 4
Message indicates a low-level loop iteration.

The format of trace messages is important because some utilities analyze trace files. There are three fields-- the time stamp, the category name, and the text. The time stamp is between square brackets and the category name between angle brackets. After the category name there is a colon (:) followed by the message text. If the square brackets or angle brackets are missing, then the trace management utilities assume that they are encountering a set of pre-formatted lines.

Note, however, that this formatting is done automatically by the tracing functions. You only need to know about it if you want to parse a trace file.

Emergency Tracing

Sometimes, you need a way for tracing to happen automatically without putting parameters in a form or on the command line. Emergency tracing does this. You invoke emergency tracing from the debug form, which is accessed from MySeedInstance/FIG/Html/SetPassword.html. Emergency tracing requires you specify a tracing key. For command-line tools, the key is taken from the TRACING environment variable. For web services, the key is taken from a cookie. Either way, the key tells the tracing facility who you are, so that you control the tracing in your environment without stepping on other users.

The key can be anything you want. If you don't have a key, the SetPassword page will generate one for you.

You can activate and de-activate emergency tracing from the debugging control panel, as well as display the trace file itself.

To enable emergency tracing in your code, call

    ETracing($cgi)

from a web script and

    ETracing()

from a command-line script.

The web script will look for the tracing key in the cookies, and the command-line script will look for it in the TRACING environment variable. If you are using the StandardScript or StandardSetup methods, emergency tracing will be configured automatically.

NOTE: to configure emergency tracing from the command line instead of the Debugging Control Panel (see below), use the trace.pl script.

Debugging Control Panel

The debugging control panel provides several tools to assist in development of SEED and Sprout software. You access the debugging control panel from the URL /FIG/Html/SetPassword.html in whichever seed instance you're using. (So, for example, the panel access point for the development NMPDR system is http://web-1.nmpdr.org/next/FIG/Html/SetPassword.html. Contact Bruce to find out what the password is. From this page, you can also specify a tracing key. If you don't specify a key, one will be generated for you.

Emergency Tracing Form

At the bottom of the debugging control panel is a form that allows you to specify a trace level and tracing categories. Special and common categories are listed with check boxes. You can hold your mouse over a check box to see what its category does. In general, however, a category name is the same as the name of the package in which the trace message occurs.

Additional categories can be entered in an input box, delimited by spaces or commas.

The Activate button turns on Emergency tracing at the level you specify with the specified categories active. The Terminate button turns tracing off. The Show File button displays the current contents of the trace file. The tracing form at the bottom of the control panel is designed for emergency tracing, so it will only affect programs that call ETracing, StandardScript, or StandardSetup.

Script Form

The top form of the debugging control panel allows you to enter a tiny script and have the output generated in a formatted table. Certain object variables are predefined in the script, including a FIG object ($fig), a CGI object ($cgi), and-- if Sprout is active-- Sprout ($sprout) and SFXlate ($sfx) objects.

The last line of the script must be a scalar, but it can be a reference to a hash, a list, a list of lists, and various other combinations. If you select the appropriate data type in the dropdown box, the output will be formatted accordingly. The form also has controls for specifying tracing. These controls override any emergency tracing in effect.

Database Query Forms

The forms between the script form and the emergency tracing form allow you to make queries against the database. The FIG query form allows simple queries against a single FIG table. The Sprout query form uses the GetAll method to do a multi-table query against the Sprout database. GetAll is located in the ERDB package, and it takes five parameters.

    GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count);

Each of the five parameters corresponds to a text box on the query form:

Objects
Comma-separated list containing the names of the entity and relationship objects to be retrieved.

Filter
WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can be parameterized with parameter markers (?). Each field used must be specified in the standard form objectName(fieldName) or $number(fieldName) where fieldName is the name of a field, objectName is the name of the entity or relationship object containing the field, and number is the 1-based position of the object in the object list. Any parameters specified in the filter clause should be specified in the Params field. The fields in a filter clause can come from primary entity relations, relationship relations, or secondary entity relations; however, all of the entities and relationships involved must be included in the list of object names.

Params
List of the parameters to be substituted in for the parameters marks in the filter clause. This is a comma-separated list without any quoting or escaping.

fields
Comma-separated list of the fields to be returned in each element of the list returned. Fields are specified in the same manner as in the filter clause.

count
Maximum number of records to return. If omitted or 0, all available records will be returned.

GetAll automatically joins together the entities and relationships listed in the object names. This simplifies the coding of the filter clause, but it means that some queries are not possible, since they cannot be expressed in a linear sequence of joins. This is a limitation that has yet to be addressed.

Public Methods

TSetup

TSetup($categoryList, $target);

This method is used to specify the trace options. The options are stored as package data and interrogated by the Trace and T methods.

categoryList
A string specifying the trace level and the categories to be traced, separated by spaces. The trace level must come first.

target
The destination for the trace output. To send the trace output to a file, specify the file name preceded by a ``>'' symbol. If a double symbol is used (``>>''), then the data is appended to the file. Otherwise the file is cleared before tracing begins. Precede the first ``>'' symbol with a + to echo output to a file AND to the standard output. In addition to sending the trace messages to a file, you can specify a special destination. HTML will cause tracing to the standard output with each line formatted as an HTML paragraph. TEXT will cause tracing to the standard output as ordinary text. ERROR will cause trace messages to be sent to the standard error output as ordinary text. QUEUE will cause trace messages to be stored in a queue for later retrieval by the QTrace method. WARN will cause trace messages to be emitted as warnings using the warn directive. NONE will cause tracing to be suppressed.

StandardSetup

my ($options, @parameters) = StandardSetup(\@categories, \%options, $parmHelp, @ARGV);

This method performs standard command-line parsing and tracing setup. The return values are a hash of the command-line options and a list of the positional parameters. Tracing is automatically set up and the command-line options are validated.

This is a complex method that does a lot of grunt work. The parameters can be more easily understood, however, once they are examined individually.

The categories parameter is the most obtuse. It is a reference to a list of special-purpose tracing categories. Most tracing categories are PERL package names. So, for example, if you wanted to turn on tracing inside the Sprout, ERDB, and SproutLoad packages, you would specify the categories

    ["Sprout", "SproutLoad", "ERDB"]

This would cause trace messages in the specified three packages to appear in the output. There are two special tracing categories that are automatically handled by this method. In other words, if you used TSetup you would need to include these categories manually, but if you use this method they are turned on automatically.

SQL
Traces SQL commands and activity.

Tracer
Traces error messages and call stacks.

SQL is only turned on if the -sql option is specified in the command line. The trace level is specified using the -trace command-line option. For example, the following command line for TransactFeatures turns on SQL tracing and runs all tracing at level 3.

    TransactFeatures -trace=3 -sql register ../xacts IDs.tbl

Standard tracing is output to the standard output and echoed to the file trace$$.log in the FIG temporary directory, where $$ is the process ID. You can also specify the user parameter to put a user ID instead of a process ID in the trace file name. So, for example

The default trace level is 2. To get all messages, specify a trace level of 4. For a genome-by-genome update, use 3.

    TransactFeatures -trace=3 -sql -user=Bruce register ../xacts IDs.tbl

would send the trace output to traceBruce.log in the temporary directory.

The options parameter is a reference to a hash containing the command-line options, their default values, and an explanation of what they mean. Command-line options may be in the form of switches or keywords. In the case of a switch, the option value is 1 if it is specified and 0 if it is not specified. In the case of a keyword, the value is separated from the option name by an equal sign. You can see this last in the command-line example above.

You can specify a different default trace level by setting $options-{trace}> prior to calling this method.

An example at this point would help. Consider, for example, the command-line utility TransactFeatures. It accepts a list of positional parameters plus the options safe, noAlias, start, and tblFiles. To start up this command, we execute the following code.

    my ($options, @parameters) = Tracer::StandardSetup(["DocUtils"],
                        { 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);

The call to C<ParseCommand> specifies the default values for the options and
stores the actual options in a hash that is returned as C<$options>. The
positional parameters are returned in C<@parameters>.

The following is a sample command line for TransactFeatures.

    TransactFeatures -trace=2 -noAlias register ../xacts IDs.tbl

Single and double hyphens are equivalent. So, you could also code the above command as

    TransactFeatures --trace=2 --noAlias register ../xacts IDs.tbl

In this case, register, ../xacts, and IDs.tbl are the positional parameters, and would find themselves in @parameters after executing the above code fragment. The tracing would be set to level 2, and the categories would be Tracer, and <DocUtils>. Tracer is standard, and DocUtils was included because it came in within the first parameter to this method. The $options hash would be

    { trace => 2, sql => 0, safe => 0,
      noAlias => 1, start => ' ', tblFiles => 0 }

Use of StandardSetup in this way provides a simple way of performing standard tracing setup and command-line parsing. Note that the caller is not even aware of the command-line switches -trace and -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.

If the background option is specified on the command line, then the 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

    -user=Bruce -background

then the trace output would go to traceBruce.log, the standard output to outBruce.log, and the error output to errBruce.log. This is designed to simplify starting a command in the background.

The user name is also used as the tracing key for Emergency Tracing. Specifying a value of E for the trace level causes emergency tracing to be used instead of custom tracing. If the user name is not specified, the tracing key is taken from the Tracing environment variable. If there is no value for that variable, the tracing key will be computed from the PID.

Finally, if the special option -help is specified, the option names will be traced at level 0 and the program will exit without processing. This provides a limited help capability. For example, if the user enters

    TransactFeatures -help

he would see the following output.

    TransactFeatures [options] <command> <transactionDirectory> <IDfile>
        -trace    tracing level (default E)
        -sql      trace SQL commands
        -safe     use database transactions
        -noAlias  do not expect aliases in CHANGE transactions
        -start    start with this genome
        -tblFiles output TBL files containing the corrected IDs

The caller has the option of modifying the tracing scheme by placing a value for trace in the incoming options hash. The default value can be overridden, or the tracing to the standard output can be turned off by suffixing a minus sign to the trace level. So, for example,

    { trace => [0, "tracing level (default 0)"],
       ...

would set the default trace level to 0 instead of E, while

    { trace => ["2-", "tracing level (default 2)"],
       ...

would set the default to 2, but trace only to the log file, not to the standard output.

The parameters to this method are as follows.

categories
Reference to a list of tracing category names. These should be names of packages whose internal workings will need to be debugged to get the command working.

options
Reference to a hash containing the legal options for the current command mapped 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 -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 trace (see above).

parmHelp
A string that vaguely describes the positional parameters. This is used if the user specifies the -h option.

argv
List of command line parameters, including the option switches, which must precede the positional parameters and be prefixed by a hyphen.

RETURN
Returns a list. The first element of the list is the reference to a hash that 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.

Setups

my $count = Tracer::Setups();

Return the number of times TSetup has been called.

This method allows for the creation of conditional tracing setups where, for example, we may want to set up tracing if nobody else has done it before us.

Open

my $handle = Open($fileHandle, $fileSpec, $message);

Open a file.

The $fileSpec is essentially the second argument of the PERL open function. The mode is specified using Unix-like shell information. So, for example,

    Open(\*LOGFILE, '>>/usr/spool/news/twitlog', "Could not open twit log.");

would open for output appended to the specified file, and

    Open(\*DATASTREAM, "| sort -u >$outputFile", "Could not open $outputFile.");

would open a pipe that sorts the records written and removes duplicates. Note the use of file handle syntax in the Open call. To use anonymous file handles, code as follows.

    my $logFile = Open(undef, '>>/usr/spool/news/twitlog', "Could not open twit log.");

The $message parameter is used if the open fails. If it is set to 0, then 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.

    Could not open "/usr/spool/news/twitlog"

Note that the mode characters are automatically cleaned from the file name. The actual error message from the file system will be captured and appended to the message in any case.

    Could not open "/usr/spool/news/twitlog": file not found.

In some versions of PERL the only error message we get is a number, which corresponds to the C++ errno value.

    Could not open "/usr/spool/news/twitlog": 6.
fileHandle
File handle. If this parameter is undef, a file handle will be generated and returned as the value of this method.

fileSpec
File name and mode, as per the PERL open function.

message (optional)
Error message to use if the open fails. If omitted, a standard error message 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 0.

RETURN
Returns the name of the file handle assigned to the file, or undef if the open failed.

FindNamePart

my ($fileName, $start, $len) = Tracer::FindNamePart($fileSpec);

Extract the portion of a file specification that contains the file name.

A file specification is the string passed to an open call. It specifies the file 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 /usr/fig/myfile.txt.

    >>/usr/fig/myfile.txt
    </usr/fig/myfile.txt
    | sort -u > /usr/fig/myfile.txt

If the method cannot find a file name using its normal methods, it will return the whole incoming string.

fileSpec
File specification string from which the file name is to be extracted.

RETURN
Returns a three-element list. The first element contains the file name portion of the specified string, or the whole string if a file name cannot be found via normal methods. The second element contains the start position of the file name portion and the third element contains the length.

OpenDir

my @files = OpenDir($dirName, $filtered, $flag);

Open a directory and return all the file names. This function essentially performs the functions of an opendir and readdir. If the $filtered parameter is set to TRUE, all filenames beginning with a period (.), dollar sign ($), or pound sign (#) and all filenames ending with a tilde ~) will be filtered out of the return list. If the directory does not open and $flag is not set, an exception is thrown. So, for example,

    my @files = OpenDir("/Volumes/fig/contigs", 1);

is effectively the same as

    opendir(TMP, "/Volumes/fig/contigs") || Confess("Could not open /Volumes/fig/contigs.");
    my @files = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir(TMP);

Similarly, the following code

    my @files = grep { $_ =~ /^\d/ } OpenDir("/Volumes/fig/orgs", 0, 1);

Returns the names of all files in /Volumes/fig/orgs that begin with digits and automatically returns an empty list if the directory fails to open.

dirName
Name of the directory to open.

filtered
TRUE if files whose names begin with a period (.) should be automatically removed from the list, else FALSE.

flag
TRUE if a failure to open is okay, else FALSE

SetLevel

Tracer::SetLevel($newLevel);

Modify the trace level. A higher trace level will cause more messages to appear.

newLevel
Proposed new trace level.

Now

my $string = Tracer::Now();

Return a displayable time stamp containing the local time.

ParseTraceDate

my $time = Tracer::ParseTraceDate($dateString);

Convert a date from the trace file into a PERL timestamp.

dateString
The date string from the trace file. The format of the string is determined by the Now method.

RETURN
Returns a PERL time, that is, a number of seconds since the epoch, or undef if the time string is invalid.

LogErrors

Tracer::LogErrors($fileName);

Route the standard error output to a log file.

fileName
Name of the file to receive the error output.

ReadOptions

my %options = Tracer::ReadOptions($fileName);

Read a set of options from a file. Each option is encoded in a line of text that has the format

optionName=optionValue; comment

The option name must consist entirely of letters, digits, and the punctuation characters . and _, 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.

fileName
Name of the file containing the option data.

RETURN
Returns a hash mapping the option names specified in the file to their corresponding option value.

GetOptions

Tracer::GetOptions(\%defaults, \%options);

Merge a specified set of options into a table of defaults. This method takes two hash references 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.

Consider the following example.

my $optionTable = GetOptions({ dbType => 'mySQL', trace => 0 }, $options);

In this example, the variable $options is expected to contain at most two options-- dbType and trace. The default database type is mySQL and the default trace level is 0. If the value of $options is {dbType => 'Oracle'}, then the database type will be changed to Oracle and the trace level will remain at 0. If $options is undefined, then the database type and trace level will remain mySQL and 0. If, on the other hand, $options is defined as

{databaseType => 'Oracle'}

an error will occur because the databaseType option does not exist.

defaults
Table of default option values.

options
Table of overrides, if any.

RETURN
Returns a reference to the default table passed in as the first parameter.

MergeOptions

Tracer::MergeOptions(\%table, \%defaults);

Merge default values into a hash table. This method looks at the key-value pairs in the 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 GetOptions, but there is no error- checking and no return value.

table
Hash table to be updated with the default values.

defaults
Default values to be merged into the first hash table if they are not already present.

Trace

Trace($message);

Write a trace message to the target location specified in TSetup. If there has not been any prior call to TSetup.

message
Message to write.

T

my $switch = T($category, $traceLevel);

    or

my $switch = T($traceLevel);

Return TRUE if the trace level is at or above a specified value and the specified category is active, else FALSE. If no category is specified, the caller's package name is used.

category
Category to which the message belongs. If not specified, the caller's package name is used.

traceLevel
Relevant tracing level.

RETURN
TRUE if a message at the specified trace level would appear in the trace, else FALSE.

ParseCommand

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 -option or -option=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.

my ($options, @arguments) = ParseCommand({ errors => 0, logFile => 'trace.log'}, @words);

In this case, the list @words will be treated as a command line and there are two options available, errors and logFile. If @words has the following format

-logFile=error.log apple orange rutabaga

then at the end of the invocation, $options will be

{ errors => 0, logFile => 'error.log' }

and @arguments will contain

apple orange rutabaga

The parser allows for some escape sequences. See UnEscape for a description. There is no support for quote characters. Options can be specified with single or double hyphens.

optionTable
Table of default options.

inputList
List of words on the command line.

RETURN
Returns a reference to the option table and a list of the positional arguments.

Escape

my $codedString = Tracer::Escape($realString);

Escape a string for use in a command length. Tabs will be replaced by \t, new-lines replaced by \n, carriage returns will be deleted, and backslashes will be doubled. The result is to reverse the effect of UnEscape.

realString
String to escape.

RETURN
Escaped equivalent of the real string.

UnEscape

my $realString = Tracer::UnEscape($codedString);

Replace escape sequences with their actual equivalents. \t will be replaced by a tab, \n by a new-line character, and \\ by a backslash. \r codes will be deleted.

codedString
String to un-escape.

RETURN
Returns a copy of the original string with the escape sequences converted to their actual values.

ParseRecord

my @fields = Tracer::ParseRecord($line);

Parse a tab-delimited data line. The data line is split into field values. Embedded tab and new-line characters in the data line must be represented as \t and \n, respectively. These will automatically be converted.

line
Line of data containing the tab-delimited fields.

RETURN
Returns a list of the fields found in the data line.

Merge

my @mergedList = Tracer::Merge(@inputList);

Sort a list of strings and remove duplicates.

inputList
List of scalars to sort and merge.

RETURN
Returns a list containing the same elements sorted in ascending order with duplicates removed.

Percent

my $percent = Tracer::Percent($number, $base);

Returns the percent of the base represented by the given number. If the base is zero, returns zero.

number
Percent numerator.

base
Percent base.

RETURN
Returns the percentage of the base represented by the numerator.

GetFile

my @fileContents = Tracer::GetFile($fileName);

    or

my $fileContents = Tracer::GetFile($fileName);

Return the entire contents of a file. In list context, line-ends are removed and each line is a list element. In scalar context, line-ends are replaced by \n.

fileName
Name of the file to read.

RETURN
In a list context, returns the entire file as a list with the line terminators removed. In a scalar context, returns the entire file as a string. If an error occurs opening the file, an empty list will be returned.

PutFile

Tracer::PutFile($fileName, \@lines);

Write out a file from a list of lines of text.

fileName
Name of the output file.

lines
Reference to a list of text lines. The lines will be written to the file in order, with trailing new-line characters. Alternatively, may be a string, in which case the string will be written without modification.

QTrace

my $data = QTrace($format);

Return the queued trace data in the specified format.

format
html to format the data as an HTML list, text to format it as straight text.

Confess

Confess($message);

Trace the call stack and abort the program with the specified message. When used with the OR operator and the Assert method, Confess can function as a debugging assert. So, for example

Assert($recNum >= 0) || Confess("Invalid record number $recNum.");

Will abort the program with a stack trace if the value of $recNum is negative.

message
Message to include in the trace.

Assert

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 Confess method as a debugging assert. So, for example

Assert($recNum >= 0) || Confess("Invalid record number $recNum.");

Will abort the program with a stack trace if the value of $recNum is negative.

Cluck

Cluck($message);

Trace the call stack. Note that for best results, you should qualify the call with a trace condition. For example,

Cluck("Starting record parse.") if T(3);

will only trace the stack if the trace level for the package is 3 or more.

message
Message to include in the trace.

Min

my $min = Min($value1, $value2, ... $valueN);

Return the minimum argument. The arguments are treated as numbers.

$value1, $value2, ... $valueN
List of numbers to compare.

RETURN
Returns the lowest number in the list.

Max

my $max = Max($value1, $value2, ... $valueN);

Return the maximum argument. The arguments are treated as numbers.

$value1, $value2, ... $valueN
List of numbers to compare.

RETURN
Returns the highest number in the list.

AddToListMap

Tracer::AddToListMap(\%hash, $key, $value1, $value2, ... valueN);

Add a key-value pair to a hash of lists. If no value exists for the key, a singleton list is created for the key. Otherwise, the new value is pushed onto the list.

hash
Reference to the target hash.

key
Key for which the value is to be added.

value1, value2, ... valueN
List of values to add to the key's value list.

DebugMode

if (Tracer::DebugMode) { ...code... }

Return TRUE if debug mode has been turned on, else abort.

Certain CGI scripts are too dangerous to exist in the production environment. This method provides a simple way to prevent them from working unless they are explicitly turned on by creating a password cookie via the SetPassword script. If debugging mode is not turned on, an error will occur.

Strip

my $string = Tracer::Strip($line);

Strip all line terminators off a string. This is necessary when dealing with files that may have been transferred back and forth several times among different operating environments.

line
Line of text to be stripped.

RETURN
The same line of text with all the line-ending characters chopped from the end.

Pad

my $paddedString = Tracer::Pad($string, $len, $left, $padChar);

Pad a string to a specified length. The pad character will be a space, and the padding will be on the right side unless specified in the third parameter.

string
String to be padded.

len
Desired length of the padded string.

left (optional)
TRUE if the string is to be left-padded; otherwise it will be padded on the right.

padChar (optional)
Character to use for padding. The default is a space.

RETURN
Returns a copy of the original string with the pad character added to the specified end so that it achieves the desired length.

EOF

This is a constant that is lexically greater than any useful string.

TICK

my @results = TICK($commandString);

Perform a back-tick operation on a command. If this is a Windows environment, any leading dot-slash (./ will be removed. So, for example, if you were doing

    `./protein.cgi`

from inside a CGI script, it would work fine in Unix, but would issue an error message in Windows complaining that '.' is not a valid command. If instead you code

    TICK("./protein.cgi")

it will work correctly in both environments.

commandString
The command string to pass to the system.

RETURN
Returns the standard output from the specified command, as a list.

ScriptSetup

my ($cgi, $varHash) = ScriptSetup($noTrace);

Perform standard tracing and debugging setup for scripts. The value returned is the CGI object followed by a pre-built variable hash. At the end of the script, the client should call ScriptFinish to output the web page.

This method calls ETracing to configure tracing, which allows the tracing to be configured via the emergency tracing form on the debugging control panel. Tracing will then be turned on automatically for all programs that use the ETracing method, which includes every program that uses this method or StandardSetup.

noTrace (optional)
If specified, tracing will be suppressed. This is useful if the script wants to set up tracing manually.

RETURN
Returns a two-element list consisting of a CGI query object and a variable hash for the output page.

ETracing

ETracing($parameter);

Set up emergency tracing. Emergency tracing is tracing that is turned on automatically for any program that calls this method. The emergency tracing parameters are stored in a a file identified by a tracing key. If this method is called with a CGI object, then the tracing key is taken from a cookie. If it is called with no parameters, then the tracing key is taken from an environment variable. If it is called with a string, the tracing key is that string.

parameter
A parameter from which the tracing key is computed. If it is a scalar, that scalar is used as the tracing key. If it is a CGI object, the tracing key is taken from the IP cookie. If it is omitted, the tracing key is taken from the TRACING environment variable. If it is a CGI object and emergency tracing is not on, the Trace and TF parameters will be used to determine the type of tracing.

EmergencyFileName

my $fileName = Tracer::EmergencyFileName($tkey);

Return the emergency tracing file name. This is the file that specifies the tracing information.

tkey
Tracing key for the current program.

RETURN
Returns the name of the file to contain the emergency tracing information.

EmergencyFileTarget

my $fileName = Tracer::EmergencyFileTarget($tkey);

Return the emergency tracing target file name. This is the file that receives the tracing output for file-based tracing.

tkey
Tracing key for the current program.

RETURN
Returns the name of the file to contain the trace output.

EmergencyTracingDest

my $dest = Tracer::EmergencyTracingDest($tkey, $myDest);

This method converts an emergency tracing destination to a real tracing destination. The main difference is that if the destination is FILE or APPEND, we convert it to file output. If the destination is DUAL, we convert it to file and standard output.

tkey
Tracing key for this environment.

myDest
Destination from the emergency tracing file.

RETURN
Returns a destination that can be passed into TSetup.

Emergency

Emergency($key, $hours, $dest, $level, @modules);

Turn on emergency tracing. This method is normally invoked over the web from a debugging console, but it can also be called by the trace.pl script. The caller specifies the duration of the emergency in hours, the desired tracing destination, the trace level, and a list of the trace modules to activate. For the length of the duration, when a program in an environment with the specified tracing key active invokes a Sprout CGI script, tracing will be turned on automatically. See TSetup for more about tracing setup and ETracing for more about emergency tracing.

tkey
The tracing key. This is used to identify the control file and the trace file.

hours
Number of hours to keep emergency tracing alive.

dest
Tracing destination. If no path information is specified for a file destination, it is put in the FIG temporary directory.

level
Tracing level. A higher level means more trace messages.

modules
A list of the tracing modules to activate.

EmergencyKey

my $tkey = EmergencyKey($parameter);

Return the Key to be used for emergency tracing. This could be an IP address, a session ID, or a user name, depending on the environment.

parameter
Parameter defining the method for finding the tracing key. If it is a scalar, then it is presumed to be the tracing key itself. If it is a CGI object, then the tracing key is taken from the IP cookie. Otherwise, the tracing key is taken from the TRACING environment variable.

RETURN
Returns the key to be used for labels in emergency tracing.

cgi
CGI query object containing the parameters to trace.

ScriptFinish

ScriptFinish($webData, $varHash);

Output a web page at the end of a script. Either the string to be output or the name of a template file can be specified. If the second parameter is omitted, it is assumed we have a string to be output; otherwise, it is assumed we have the name of a template file. The template should have the variable 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 BODY tag in the output, formatted as a list.

A typical standard script would loook like the following.

    BEGIN {
        # Print the HTML header.
        print "CONTENT-TYPE: text/html\n\n";
    }
    use Tracer;
    use CGI;
    use FIG;
    # ... more uses ...
    my ($cgi, $varHash) = ScriptSetup();
    eval {
        # ... get data from $cgi, put it in $varHash ...
    };
    if ($@) {
        Trace("Script Error: $@") if T(0);
    }
    ScriptFinish("Html/MyTemplate.html", $varHash);

The idea here is that even if the script fails, you'll see trace messages and useful output.

webData
A string containing either the full web page to be written to the output or the 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.

varHash (optional)
If specified, then a reference to a hash mapping variable names for a template to their values. The template file will be read into memory, and variable markers will be replaced by data in this hash reference.

Insure

Insure($dirName, $chmod);

Insure a directory is present.

dirName
Name of the directory to check. If it does not exist, it will be created.

chmod (optional)
Security privileges to be given to the directory if it is created.

ChDir

ChDir($dirName);

Change to the specified directory.

dirName
Name of the directory to which we want to change.

SendSMS

my $msgID = Tracer::SendSMS($phoneNumber, $msg);

Send a text message to a phone number using Clickatell. The FIG_Config file must contain the user name, password, and API ID for the relevant account in the hash reference variable $FIG_Config::phone, using the keys user, password, and api_id. For example, if the user name is BruceTheHumanPet, the password is silly, and the API ID is 2561022, then the FIG_Config file must contain

    $phone =  { user => 'BruceTheHumanPet',
                password => 'silly',
                api_id => '2561022' };

The original purpose of this method was to insure Bruce would be notified immediately when the Sprout Load terminates. Care should be taken if you do not wish Bruce to be notified immediately when you call this method.

The message ID will be returned if successful, and undef if an error occurs.

phoneNumber
Phone number to receive the message, in international format. A United States phone number would be prefixed by ``1''. A British phone number would be prefixed by ``44''.

msg
Message to send to the specified phone.

RETURN
Returns the message ID if successful, and undef if the message could not be sent.

CommaFormat

my $formatted = Tracer::CommaFormat($number);

Insert commas into a number.

number
A sequence of digits.

RETURN
Returns the same digits with commas strategically inserted.

dirName
Name of the directory to process.

group
Name of the group to be assigned.

mask
Permission mask. Bits that are 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.

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 tmp.
    Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp$' => 01777);

The list is ordered, so the following would use 0777 for tmp1 and 0666 for tmp, tmp2, or 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.

CompareLists

my ($inserted, $deleted) = Tracer::CompareLists(\@newList, \@oldList, $keyIndex);

Compare two lists of tuples, and return a hash analyzing the differences. The lists are presumed to be sorted alphabetically by the value in the $keyIndex column. The return value contains a list of items that are only in the new list (inserted) and only in the old list (deleted).

newList
Reference to a list of new tuples.

oldList
Reference to a list of old tuples.

keyIndex (optional)
Index into each tuple of its key field. The default is 0.

RETURN
Returns a 2-tuple consisting of a reference to the list of items that are only in the new list (inserted) followed by a reference to the list of items that are only in the old list (deleted).

GetLine

my @data = Tracer::GetLine($handle);

Read a line of data from a tab-delimited file.

handle
Open file handle from which to read.

RETURN
Returns a list of the fields in the record read. The fields are presumed to be tab-delimited. If we are at the end of the file, then an empty list will be returned. If an empty line is read, a single list item consisting of a null string will be returned.

PutLine

Tracer::PutLine($handle, \@fields, $eol);

Write a line of data to a tab-delimited file. The specified field values will be output in tab-separated form, with a trailing new-line.

handle
Output file handle.

fields
List of field values.

eol (optional)
End-of-line character (default is ``\n'').

GenerateURL

my $queryUrl = Tracer::GenerateURL($page, %parameters);

Generate a GET-style URL for the specified page with the specified parameter names and values. The values will be URL-escaped automatically. So, for example

    Tracer::GenerateURL("form.cgi", type => 1, string => "\"high pass\" or highway")

would return

    form.cgi?type=1;string=%22high%20pass%22%20or%20highway
page
Page URL.

parameters
Hash mapping parameter names to parameter values.

RETURN
Returns a GET-style URL that goes to the specified page and passes in the specified parameters and values.

ApplyURL

Tracer::ApplyURL($table, $target, $url);

Run through a two-dimensional table (or more accurately, a list of lists), converting the $target column to HTML text having a hyperlink to a URL in the $url column. The URL column will be deleted by this process and the target column will be HTML-escaped.

This provides a simple way to process the results of a database query into something displayable by combining a URL with text.

table
Reference to a list of lists. The elements in the containing list will be updated by this method.

target
The index of the column to be converted into HTML.

url
The index of the column containing the URL. Note that the URL must have a recognizable http: at the beginning.

CombineURL

my $combinedHtml = Tracer::CombineURL($text, $url);

This method will convert the specified text into HTML hyperlinked to the specified URL. The hyperlinking will only take place if the URL looks legitimate: that is, it is defined and begins with an http: header.

text
Text to return. This will be HTML-escaped automatically.

url
A URL to be hyperlinked to the text. If it does not look like a URL, then the text will be returned without any hyperlinking.

RETURN
Returns the original text, HTML-escaped, with the URL hyperlinked to it. If the URL doesn't look right, the HTML-escaped text will be returned without any further modification.