package TIGR::Foundation; { =head1 NAME TIGR::Foundation - TIGR Foundation object =head1 SYNOPSIS use TIGR::Foundation; my $obj_instance = new TIGR::Foundation; =head1 DESCRIPTION This module defines a structure for Perl programs to utilize logging, version reporting, and dependency checking in a simple way. =cut BEGIN { require 5.006_00; # error if using Perl < v5.6.0 } use strict; use Cwd; use Cwd 'chdir'; use Cwd 'abs_path'; use File::Basename; use Getopt::Long; use IO::Handle; use POSIX qw(strftime); use Sys::Hostname; use English; require Exporter; our @ISA; our @EXPORT; @ISA = ('Exporter'); @EXPORT = qw( isReadableFile isWritableFile isExecutableFile isCreatableFile isReadableDir isWritableDir isCreatableDir isCreatablePath getISODate getSybaseDate getMySQLDate getFilelabelDate getLogfileDate ); ## internal variables and identifiers our $REVISION = (qw$Revision: 1.1.1.1 $)[-1]; our $VERSION = '1.1'; our $VERSION_STRING = "$VERSION (Build $REVISION)"; our @DEPEND = (); # there are no dependencies ## prototypes # Functional Class : general sub new(); sub getProgramInfo($); sub runCommand($); # Functional Class : depend sub printDependInfo(); sub printDependInfoAndExit(); sub addDependInfo(@); # Functional Class : version sub getVersionInfo(); sub printVersionInfo(); sub printVersionInfoAndExit(); sub setVersionInfo($); # Functional Class : help sub printHelpInfo(); sub printHelpInfoAndExit(); sub setHelpInfo($); # Functional Class : usage sub printUsageInfo(); sub printUsageInfoAndExit(); sub setUsageInfo($); # Functional Class : files sub isReadableFile($); sub isExecutableFile($); sub isWritableFile($); sub isCreatableFile($); sub isReadableDir($); sub isWritableDir($); sub isCreatableDir($); sub isCreatablePath($); # Functional Class : date sub getISODate(;@); sub getSybaseDate(;@); sub getMySQLDate(;@); sub getFilelabelDate(;@); sub getLogfileDate(;@); # Functional Class : logging sub setDebugLevel($;$); sub getDebugLevel(); sub setLogFile($;$); sub getLogFile(); sub getErrorFile(); sub printDependInfo(); sub invalidateLogFILES(); sub cleanLogFILES(); sub closeLogERROR(); sub closeLogMSG(); sub openLogERROR(); sub openLogMSG(); sub logAppend($;$); sub debugPush(); sub debugPop(); sub logLocal($$); sub logError($;$); sub bail($;$); # Functional Class : modified methods sub TIGR_GetOptions(@); ## Implementation # Functional Class : general =over =item $obj_instance = new TIGR::Foundation; This function creates a new instance of the TIGR::Foundation object. A reference pointing to the object is returned on success. Otherwise, this method returns undefined. =cut sub new() { my $self = {}; my $pkg = shift; my $user_name = getpwuid($<); my $host_name = hostname(); # create the object bless $self, $pkg; ## Instance variables and identifiers, by functional class # Functional Class : general my $pname = basename($0, ()); # extract the script name if((defined ($pname)) && ($pname =~ /^(.*)$/)) { $pname = $1; $self->{program_name} = $pname ; } if ($self->{program_name} =~ /^-$/) { # check if '-' is the input $self->{program_name} = "STDIN"; } my $pcommand = join (' ', @ARGV); if((defined ($pcommand)) && ($pcommand =~ /^(.*)$/)) { $pcommand = $1; $self->{invocation} = $pcommand ; } # The following four variables are to contain information specified by # the 'host' program; there are methods of setting and retrieving each # Functional Class : depend @{$self->{depend_info}} = (); # Functional Class : version $self->{version_info} = undef; # Functional Class : help $self->{help_info} = undef; # Functional Class : usage $self->{usage_info} = undef; # Functional Class : logging $self->{debug_level} = undef; # default debug is not defined @{$self->{debug_store}} = (); # the backup debug level stack @{$self->{debug_queue}} = (); # queue used by MSG routine @{$self->{error_queue}} = (); # queue used by ERROR routine $self->{max_debug_queue_size} = 100; # maximum size for queue before # log entries are expired @{$self->{log_files}} = # these log files are consulted ("$self->{program_name}.log", # on file write error and are "/tmp/$self->{program_name}.$$.log"); # modified by setLogFile $self->{msg_file_open_flag} = 0; # flag to check logLocal file $self->{error_file_open_flag} = 0; # flag to check logError file $self->{msg_file_used} = 0; # flag to indicate if log file $self->{error_file_used} = 0; # has been written to $self->{msg_append_flag} = 0; # by default logs are truncated $self->{error_append_flag} = 0; # by default logs are truncated $self->{log_append_setting} = 0; # (truncate == 0) $self->{static_log_file} = undef; # user defined log file $self->{start_time} = undef; # program start time $self->{finish_time} = undef; # program stop time # Log program invocation $self->logLocal("START: " . "Username:$user_name, ". "Hostname: $host_name ". $self->getProgramInfo('name') . " " . $self->getProgramInfo('invocation'), 0); $self->{start_time} = time; return $self; } =item $value = $obj_instance->getProgramInfo($field_type); This function returns field values for specified field types describing attributes of the program. The C<$field_type> parameter must be a listed attribute: C, C, C, C. The C field specifies the bare name of the executable. The C field specifies the command line arguments passed to the executable. The C value returns the environment path to the working directory. The C value specifies the absolute path to the working directory. If C is found to be inconsistent, then that value will return the C value. If an invalid C<$field_type> is passed, the function returns undefined. =cut sub getProgramInfo($) { my $self = shift; my $field_type = shift; my $return_value = undef; if (defined $field_type) { $field_type =~ /^name$/ && do { $return_value = $self->{program_name}; }; $field_type =~ /^invocation$/ && do { $return_value = $self->{invocation}; }; $field_type =~ /^env_path$/ && do { my $return_value = ""; if ( (defined $ENV{'PWD'}) && (abs_path($ENV{'PWD'}) eq abs_path(".")) && ($ENV{'PWD'} =~ /^(.*)$/) ) { $ENV{'PWD'} = $1; $return_value = $ENV{'PWD'}; } else { my $tmp_val = abs_path("."); if((defined ($tmp_val)) && ($tmp_val =~ /^(.*)$/)) { $tmp_val = $1; $return_value = $tmp_val; } } return $return_value; }; $field_type =~ /^abs_path$/ && do { my $tmp_val = abs_path("."); if((defined ($tmp_val)) && ($tmp_val =~ /^(.*)$/)) { $tmp_val = $1; $return_value = $tmp_val; } }; } return $return_value; } =item $exit_code = $obj_instance->runCommand($command_str); This function passes the argument C<$command_str> to /bin/sh for processing. The return value is the exit code of the C<$command_str>. If the exit code is not defined, then either the signal or core dump value of the execution is returned, whichever is applicable. Perl variables C<$?> and C<$!> are set accordingly. If C<$command_str> is not defined, this function returns undefined. Log messages are recorded at log level 4 to indicate the type of exit status and the corresponding code. Invalid commands return -1. =cut sub runCommand($) { my $self = shift; my $command_str = shift; my $exit_code = undef; my $signal_num = undef; my $dumped_core = undef; my $invalid_command = undef; my $return_value = undef; my @info_arr = getpwuid($<); my $len = @info_arr; my $home_dir = $info_arr[7]; my $current_dir = $self->getProgramInfo("abs_path"); if((defined ($ENV{PATH})) && ($ENV{PATH} =~ /^(.*)$/)) {#taint checking $ENV{PATH} = $1; my $path_var = $ENV{PATH}; my @paths = split /:/, $path_var; my $pathval = undef; my $i = 0; my $paths_len = @paths; for ($i = 0; $i < $paths_len ; $i++) { #substituting ~ with the home pathname. $pathval = $paths[$i]; $pathval =~ s/^~$/$home_dir/g; my $home_root = $home_dir."\/"; $pathval =~ s/^~\//$home_root/g; #substituting . with the current pathname. $pathval =~ s/^\.$/$current_dir/g; my $current_root = $current_dir."\/"; $pathval =~ s/^\.\//$current_root/g; $paths[$i] = $pathval; } $ENV{PATH} = join(":", @paths); } if((defined ($command_str)) && ($command_str =~ /^(.*)$/)) {#taint #checking $command_str = $1; system($command_str); $exit_code = $? >> 8; $signal_num = $? & 127; $dumped_core = $? & 128; if ($? == -1) { $invalid_command = -1; } if ( (!defined $invalid_command) && ($exit_code == 0) && ($signal_num == 0) && ($dumped_core != 0) ) { $self->logLocal("Command '" . $command_str . "' core dumped", 4); $return_value = $dumped_core; } elsif ( (!defined $invalid_command) && ($exit_code == 0) && ($signal_num != 0) ) { $self->logLocal("Command '" . $command_str . "' exited on signal " . $signal_num, 4); $return_value = $signal_num; } elsif ((!defined $invalid_command)) { $self->logLocal("Command '" . $command_str . "' exited with exit code " . $exit_code, 4); $return_value = $exit_code; } else { $self->logLocal("Command '" . $command_str . "' exited with invalid code " . $?, 4); $return_value = $?; } } return $return_value; } # Functional Class : depend =item $obj_instance->printDependInfo(); The C function prints the dependency list created by C. One item is printed per line. =cut sub printDependInfo() { my $self = shift; foreach my $dependent (@{$self->{depend_info}}) { print STDERR $dependent, "\n"; } } =item $obj_instance->printDependInfoAndExit(); The C function prints the dependency list created by C. One item is printed per line. The function exits with exit code 0. =cut sub printDependInfoAndExit() { my $self = shift; $self->printDependInfo(); exit 0; } =item $obj_instance->addDependInfo(@depend_list); The C function adds C<@depend_list> information to the dependency list. If C<@depend_list> is empty, the internal dependency list is emptied. Contents of C<@depend_list> are not checked for validity (eg. they can be composed entirely of white space or multiple files per record). The first undefined record in C<@depend_list> halts reading in of dependency information. =cut sub addDependInfo(@) { my $self = shift; my $num_elts = 0; while (my $data_elt = shift @_) { push (@{$self->{depend_info}}, $data_elt); $num_elts++; } if ($num_elts == 0) { @{$self->{depend_info}} = (); } } # Functional Class : version =item $version_string = $obj_instance->getVersionInfo(); The C function returns the version information set by the C function. =cut sub getVersionInfo() { my $self = shift; return $self->{version_info}; } =item $obj_instance->printVersionInfo(); The C function prints the version information set by the C function. If there is no defined version information, a message is returned notifying the user. =cut sub printVersionInfo() { my $self = shift; if (defined $self->getVersionInfo()) { print STDERR $self->getProgramInfo('name'), " ", $self->getVersionInfo(), "\n"; } else { print STDERR $self->getProgramInfo('name'), " has no defined version information\n"; } } =item $obj_instance->printVersionInfoAndExit(); The C function prints version info set by the C function. If there is no defined version information, a message is printed notifying the user. This function calls exit with exit code 0. =cut sub printVersionInfoAndExit() { my $self = shift; $self->printVersionInfo(); exit 0; } =item $obj_instance->setVersionInfo($version_string); The C function sets the version information to be reported by C. If C<$version_string> is empty, invalid, or undefined, the stored version information will be undefined. =cut sub setVersionInfo($) { my $self = shift; my $v_info = shift; if ( (defined $v_info) && ($v_info =~ /\S/) && ((ref $v_info) eq "") ) { $self->{version_info} = $v_info; } else { $self->{version_info} = undef; } } # Functional Class : help =item $obj_instance->printHelpInfo(); The C function prints the help information passed by the C function. =cut sub printHelpInfo() { my $self = shift; if (defined $self->{help_info}) { print STDERR $self->{help_info}; } else { print STDERR "No help information defined.\n"; } } =item $obj_instance->printHelpInfoAndExit(); The C function prints the help info passed by the C function. This function exits with exit code 0. =cut sub printHelpInfoAndExit() { my $self = shift; $self->printHelpInfo(); exit 0; } =item $obj_instance->setHelpInfo($help_string); The C function sets the help information via C<$help_string>. If C<$help_string> is undefined, invalid, or empty, the help information is undefined. =cut sub setHelpInfo($) { my $self = shift; my $help_string = shift; if ( (defined $help_string) && ($help_string =~ /\S/) && ((ref $help_string) eq "") ) { chomp($help_string);#removing a new line if it is there. $self->{help_info} = $help_string."\n";#adding a new line to help. } else { $self->{help_info} = undef; } } # Functional Class : usage =item $obj_instance->printUsageInfo(); The C function prints the usage information reported by the C function. If no usage information is defined, but help information is defined, help information will be printed. =cut sub printUsageInfo() { my $self = shift; if (defined $self->{usage_info}) { print STDERR $self->{usage_info}; } elsif (defined $self->{help_info}) { print STDERR $self->{help_info}; } else { print STDERR "No usage information defined.\n"; } } =item $obj_instance->printUsageInfoAndExit(); The C function prints the usage information the reported by the C function and exits with status 1. =cut sub printUsageInfoAndExit() { my $self = shift; $self->printUsageInfo(); $self->bail("Incorrect command line"); } =item $obj_instance->setUsageInfo($usage_string); The C function sets the usage information via C<$usage_string>. If C<$usage_string> is undefined, invalid, or empty, the usage information is undefined. =cut sub setUsageInfo($) { my $self = shift; my $usage_string = shift; if ( (defined $usage_string) && ($usage_string =~ /\S/) && ((ref $usage_string) eq "") ) { chomp($usage_string); #removing a new line if it is there. $self->{usage_info} = $usage_string."\n";#adding a new line to usage } else { $self->{usage_info} = undef; } } # Functional Class : files =item $valid = isReadableFile($file_name); This function accepts a single scalar parameter containing a file name. If the file corresponding to the file name is a readable plain file or symbolic link, this function returns 1. Otherwise, the function returns 0. If the file name passed is undefined, this function returns 0 as well. =cut sub isReadableFile($) { my $file = shift; if (scalar(@_) != 0) { #incase the method was invoked as an instance #method $file = shift; } if (defined ($file) && # was a file name passed? ((-f $file) || (-l $file)) && # is the file a file or sym. link? (-r $file) # is the file readable? ) { return 1; } else { return 0; } } =item $valid = isExecutableFile($file_name); This function accepts a single scalar parameter containing a file name. If the file corresponding to the file name is an executable plain file or symbolic link, this function returns 1. Otherwise, the function returns 0. If the file name passed is undefined, this function returns 0 as well. =cut sub isExecutableFile($) { my $file = shift; if (scalar(@_) != 0) { # incase the method was invoked as a instance # method $file = shift; } if (defined ($file) && # was a file name passed? ((-f $file) || (-l $file)) && # is the file a file or sym. link? (-x $file) # is the file executable? ) { return 1; } else { return 0; } } =item $valid = isWritableFile($file_name); This function accepts a single scalar parameter containing a file name. If the file corresponding to the file name is a writable plain file or symbolic link, this function returns 1. Otherwise, the function returns 0. If the file name passed is undefined, this function returns 0 as well. =cut sub isWritableFile($) { my $file = shift; if (scalar(@_) != 0) { # incase the method was invoked as a instance # method $file = shift; } if (defined ($file) && # was a file name passed? ((-f $file) || (-l $file)) && # is the file a file or sym. link? (-w $file) # is the file writable? ) { return 1; } else { return 0; } } =item $valid = isCreatableFile($file_name); This function accepts a single scalar parameter containing a file name. If the file corresponding to the file name is creatable this function returns 1. The function checks if the location of the file is writable by the effective user id (EUID). If the file location does not exist or the location is not writable, the function returns 0. If the file name passed is undefined, this function returns 0 as well. Note that files with suffix F are not supported under UNIX platforms, and will return 0. =cut sub isCreatableFile($) { my $file = shift; if (scalar(@_) != 0) { # incase the method was invoked as an instance # method $file = shift; } my $return_code = 0; if ( (defined ($file)) && (! -e $file) && ($file !~ /\/$/) ) { my $dirname = dirname($file); # check the writability of the directory $return_code = isWritableDir($dirname); } else { # the file exists, it's not creatable $return_code = 0; } return $return_code; } =item $valid = isReadableDir($directory_name); This function accepts a single scalar parameter containing a directory name. If the name corresponding to the directory is a readable, searchable directory entry, this function returns 1. Otherwise, the function returns 0. If the name passed is undefined, this function returns 0 as well. =cut sub isReadableDir($) { my $file = shift; if (scalar(@_) != 0) { # incase the method was invoked as an instance # method $file = shift; } if (defined ($file) && # was a name passed? (-d $file) && # is the name a directory? (-r $file) && # is the directory readable? (-x $file) # is the directory searchable? ) { return 1; } else { return 0; } } =item $valid = isWritableDir($directory_name); This function accepts a single scalar parameter containing a directory name. If the name corresponding to the directory is a writable, searchable directory entry, this function returns 1. Otherwise, the function returns 0. If the name passed is undefined, this function returns 0 as well. =cut sub isWritableDir($) { my $file = shift; if (scalar(@_) != 0) { # incase the method was invoked as an instance # method $file = shift; } if (defined ($file) && # was a name passed? (-d $file) && # is the name a directory? (-w $file) && # is the directory writable? (-x $file) # is the directory searchable? ) { return 1; } else { return 0; } } =item $valid = isCreatableDir($directory_name); This function accepts a single scalar parameter containing a directory name. If the name corresponding to the directory is creatable this function returns 1. The function checks if the immediate parent of the directory is writable by the effective user id (EUID). If the parent directory does not exist or the tree is not writable, the function returns 0. If the directory name passed is undefined, this function returns 0 as well. =cut sub isCreatableDir($) { my $dir = shift; if (scalar(@_) != 0) { # incase the method was invoked as an instance # method $dir = shift; } my $return_code = 0; if (defined ($dir)) { $dir =~ s/\/$//g; $return_code = isCreatableFile($dir); } return $return_code; } =item $valid = isCreatablePath($path_name); This function accepts a single scalar parameter containing a path name. If the C<$path_name> is creatable this function returns 1. The function checks if the directory hierarchy of the path is creatable or writable by the effective user id (EUID). This function calls itself recursively until an existing directory node is found. If that node is writable, ie. the path can be created in it, then this function returns 1. Otherwise, the function returns 0. This function also returns zero if the C<$path_name> supplied is disconnected from a reachable directory tree on the file system. If the path already exists, this function returns 0. The C<$path_name> may imply either a path to a file or a directory. Path names may be relative or absolute paths. Any unresolvable relative paths will return 0 as well. This includes paths with F<..> back references to nonexistent directories. This function is recursive whereas C and C are not. =cut sub isCreatablePath($) { my $pathname = shift; if (scalar(@_) != 0) { # incase the method was invoked as an instance # method $pathname = shift; } my $return_code = 0; if (defined $pathname) { # strip trailing '/' $pathname =~ s/(.+)\/$/$1/g; my $filename = basename($pathname); my $dirname = dirname($pathname); if ( (! -e $pathname) && ($dirname ne $pathname) && ($filename ne "..") ) { if (-e $dirname) { $return_code = isWritableDir($dirname); } else { $return_code = isCreatablePath($dirname); } } else { $return_code = 0; } } return $return_code; } # Functional Class : date =item $date_string = getISODate($tm); This function returns the ISO 8601 datetime as a string given a time structure as returned by the C