[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.47, Thu Jun 8 13:52:23 2006 UTC revision 1.61, Fri Jul 28 02:03:04 2006 UTC
# Line 30  Line 30 
30      use Digest::MD5;      use Digest::MD5;
31      use File::Basename;      use File::Basename;
32      use File::Path;      use File::Path;
33        use File::stat;
34        use LWP::UserAgent;
35    
36  =head1 Tracing and Debugging Helpers  =head1 Tracing and Debugging Helpers
37    
# Line 1347  Line 1349 
1349      return @inputList;      return @inputList;
1350  }  }
1351    
1352    =head3 Percent
1353    
1354    C<< my $percent = Tracer::Percent($number, $base); >>
1355    
1356    Returns the percent of the base represented by the given number. If the base
1357    is zero, returns zero.
1358    
1359    =over 4
1360    
1361    =item number
1362    
1363    Percent numerator.
1364    
1365    =item base
1366    
1367    Percent base.
1368    
1369    =item RETURN
1370    
1371    Returns the percentage of the base represented by the numerator.
1372    
1373    =back
1374    
1375    =cut
1376    
1377    sub Percent {
1378        # Get the parameters.
1379        my ($number, $base) = @_;
1380        # Declare the return variable.
1381        my $retVal = 0;
1382        # Compute the percent.
1383        if ($base != 0) {
1384            $retVal = $number * 100 / $base;
1385        }
1386        # Return the result.
1387        return $retVal;
1388    }
1389    
1390  =head3 GetFile  =head3 GetFile
1391    
1392  C<< my @fileContents = Tracer::GetFile($fileName); >>  C<< my @fileContents = Tracer::GetFile($fileName); >>
# Line 1380  Line 1420 
1420      # Declare the return variable.      # Declare the return variable.
1421      my @retVal = ();      my @retVal = ();
1422      # Open the file for input.      # Open the file for input.
1423      my $ok = open INPUTFILE, "<$fileName";      my $handle = Open(undef, "<$fileName");
     if (!$ok) {  
         # If we had an error, trace it. We will automatically return a null value.  
         Trace("Could not open \"$fileName\" for input: $!") if T(0);  
     } else {  
1424          # Read the whole file into the return variable, stripping off any terminator          # Read the whole file into the return variable, stripping off any terminator
1425          # characters.          # characters.
1426          my $lineCount = 0;          my $lineCount = 0;
1427          while (my $line = <INPUTFILE>) {      while (my $line = <$handle>) {
1428              $lineCount++;              $lineCount++;
1429              $line = Strip($line);              $line = Strip($line);
1430              push @retVal, $line;              push @retVal, $line;
1431          }          }
1432          # Close it.          # Close it.
1433          close INPUTFILE;      close $handle;
1434          my $actualLines = @retVal;          my $actualLines = @retVal;
     }  
1435      # Return the file's contents in the desired format.      # Return the file's contents in the desired format.
1436      if (wantarray) {      if (wantarray) {
1437          return @retVal;          return @retVal;
# Line 1405  Line 1440 
1440      }      }
1441  }  }
1442    
1443    =head3 PutFile
1444    
1445    C<< Tracer::PutFile($fileName, \@lines); >>
1446    
1447    Write out a file from a list of lines of text.
1448    
1449    =over 4
1450    
1451    =item fileName
1452    
1453    Name of the output file.
1454    
1455    =item lines
1456    
1457    Reference to a list of text lines. The lines will be written to the file in order, with trailing
1458    new-line characters.
1459    
1460    =back
1461    
1462    =cut
1463    
1464    sub PutFile {
1465        # Get the parameters.
1466        my ($fileName, $lines) = @_;
1467        # Open the output file.
1468        my $handle = Open(undef, ">$fileName");
1469        # Write the lines.
1470        for my $line (@{$lines}) {
1471            print $handle "$line\n";
1472        }
1473        # Close the output file.
1474        close $handle;
1475    }
1476    
1477  =head3 QTrace  =head3 QTrace
1478    
1479  C<< my $data = QTrace($format); >>  C<< my $data = QTrace($format); >>
# Line 1605  Line 1674 
1674    
1675  =head3 AddToListMap  =head3 AddToListMap
1676    
1677  C<< Tracer::AddToListMap(\%hash, $key, $value); >>  C<< Tracer::AddToListMap(\%hash, $key, $value1, $value2, ... valueN); >>
1678    
1679  Add a key-value pair to a hash of lists. If no value exists for the key, a singleton list  Add a key-value pair to a hash of lists. If no value exists for the key, a singleton list
1680  is created for the key. Otherwise, the new value is pushed onto the list.  is created for the key. Otherwise, the new value is pushed onto the list.
# Line 1620  Line 1689 
1689    
1690  Key for which the value is to be added.  Key for which the value is to be added.
1691    
1692  =item value  =item value1, value2, ... valueN
1693    
1694  Value to add to the key's value list.  List of values to add to the key's value list.
1695    
1696  =back  =back
1697    
# Line 1630  Line 1699 
1699    
1700  sub AddToListMap {  sub AddToListMap {
1701      # Get the parameters.      # Get the parameters.
1702      my ($hash, $key, $value) = @_;      my ($hash, $key, @values) = @_;
1703      # Process according to whether or not the key already has a value.      # Process according to whether or not the key already has a value.
1704      if (! exists $hash->{$key}) {      if (! exists $hash->{$key}) {
1705          $hash->{$key} = [$value];          $hash->{$key} = [@values];
1706      } else {      } else {
1707          push @{$hash->{$key}}, $value;          push @{$hash->{$key}}, @values;
1708      }      }
1709  }  }
1710    
# Line 1665  Line 1734 
1734          $retVal = 1;          $retVal = 1;
1735      } else {      } else {
1736          # Here debug mode is off, so we generate an error page.          # Here debug mode is off, so we generate an error page.
1737          my $pageString = PageBuilder::Build("<Html/ErrorPage.html", {}, "Html");          my $pageString = PageBuilder::Build("<<Html/ErrorPage.html", {}, "Html");
1738          print $pageString;          print $pageString;
1739      }      }
1740      # Return the determination indicator.      # Return the determination indicator.
# Line 1933  Line 2002 
2002      my $outputString;      my $outputString;
2003      if (defined $varHash) {      if (defined $varHash) {
2004          # Here we have a template file. We need to apply the variables to the template.          # Here we have a template file. We need to apply the variables to the template.
2005          $outputString = PageBuilder::Build("<$webData", $varHash, "Html");          $outputString = PageBuilder::Build("<<$webData", $varHash, "Html");
2006      } else {      } else {
2007          # Here the user gave us a raw string.          # Here the user gave us a raw string.
2008          $outputString = $webData;          $outputString = $webData;
# Line 2009  Line 2078 
2078      }      }
2079  }  }
2080    
2081    =head3 SendSMS
2082    
2083    C<< my $msgID = Tracer::SendSMS($phoneNumber, $msg); >>
2084    
2085    Send a text message to a phone number using Clickatell. The FIG_Config file must contain the
2086    user name, password, and API ID for the relevant account in the hash reference variable
2087    I<$FIG_Config::phone>, using the keys C<user>, C<password>, and C<api_id>. For
2088    example, if the user name is C<BruceTheHumanPet>, the password is C<silly>, and the API ID
2089    is C<2561022>, then the FIG_Config file must contain
2090    
2091        $phone =  { user => 'BruceTheHumanPet',
2092                    password => 'silly',
2093                    api_id => '2561022' };
2094    
2095    The original purpose of this method was to insure Bruce would be notified immediately when the
2096    Sprout Load terminates. Care should be taken if you do not wish Bruce to be notified immediately
2097    when you call this method.
2098    
2099    The message ID will be returned if successful, and C<undef> if an error occurs.
2100    
2101    =over 4
2102    
2103    =item phoneNumber
2104    
2105    Phone number to receive the message, in international format. A United States phone number
2106    would be prefixed by "1". A British phone number would be prefixed by "44".
2107    
2108    =item msg
2109    
2110    Message to send to the specified phone.
2111    
2112    =item RETURN
2113    
2114    Returns the message ID if successful, and C<undef> if the message could not be sent.
2115    
2116    =back
2117    
2118    =cut
2119    
2120    sub SendSMS {
2121        # Get the parameters.
2122        my ($phoneNumber, $msg) = @_;
2123        # Declare the return variable. If we do not change it, C<undef> will be returned.
2124        my $retVal;
2125        # Only proceed if we have phone support.
2126        if (! defined $FIG_Config::phone) {
2127            Trace("Phone support not present in FIG_Config.") if T(1);
2128        } else {
2129            # Get the phone data.
2130            my $parms = $FIG_Config::phone;
2131            # Get the Clickatell URL.
2132            my $url = "http://api.clickatell.com/http/";
2133            # Create the user agent.
2134            my $ua = LWP::UserAgent->new;
2135            # Request a Clickatell session.
2136            my $resp = $ua->post("$url/sendmsg", { user => $parms->{user},
2137                                         password => $parms->{password},
2138                                         api_id => $parms->{api_id},
2139                                         to => $phoneNumber,
2140                                         text => $msg});
2141            # Check for an error.
2142            if (! $resp->is_success) {
2143                Trace("Alert failed.") if T(1);
2144            } else {
2145                # Get the message ID.
2146                my $rstring = $resp->content;
2147                if ($rstring =~ /^ID:\s+(.*)$/) {
2148                    $retVal = $1;
2149                } else {
2150                    Trace("Phone attempt failed with $rstring") if T(1);
2151                }
2152            }
2153        }
2154        # Return the result.
2155        return $retVal;
2156    }
2157    
2158    =head3 CommaFormat
2159    
2160    C<< my $formatted = Tracer::CommaFormat($number); >>
2161    
2162    Insert commas into a number.
2163    
2164    =over 4
2165    
2166    =item number
2167    
2168    A sequence of digits.
2169    
2170    =item RETURN
2171    
2172    Returns the same digits with commas strategically inserted.
2173    
2174    =back
2175    
2176    =cut
2177    
2178    sub CommaFormat {
2179        # Get the parameters.
2180        my ($number) = @_;
2181        # Pad the length up to a multiple of three.
2182        my $padded = "$number";
2183        $padded = " " . $padded while length($padded) % 3 != 0;
2184        # This is a fancy PERL trick. The parentheses in the SPLIT pattern
2185        # cause the delimiters to be included in the output stream. The
2186        # GREP removes the empty strings in between the delimiters.
2187        my $retVal = join(",", grep { $_ ne '' } split(/(...)/, $padded));
2188        # Clean out the spaces.
2189        $retVal =~ s/ //g;
2190        # Return the result.
2191        return $retVal;
2192    }
2193  =head3 SetPermissions  =head3 SetPermissions
2194    
2195  C<< Tracer::SetPermissions($dirName, $group, $mask); >>  C<< Tracer::SetPermissions($dirName, $group, $mask, %otherMasks); >>
2196    
2197  Set the permissions for a directory and all the files and folders inside it.  Set the permissions for a directory and all the files and folders inside it.
2198  In addition, the group ownership will be changed to the specified value.  In addition, the group ownership will be changed to the specified value.
# Line 2035  Line 2216 
2216  permission bits of any file or directory that does not already have them  permission bits of any file or directory that does not already have them
2217  set to 1.  set to 1.
2218    
2219    =item otherMasks
2220    
2221    Map of search patterns to permission masks. If a directory name matches
2222    one of the patterns, that directory and all its members and subdirectories
2223    will be assigned the new pattern. For example, the following would
2224    assign 01664 to most files, but would use 01777 for directories named C<tmp>.
2225    
2226        Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp$' => 01777);
2227    
2228    The list is ordered, so the following would use 0777 for C<tmp1> and
2229    0666 for C<tmp>, C<tmp2>, or C<tmp3>.
2230    
2231        Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp1' => 0777,
2232                                                       '^tmp' => 0666);
2233    
2234    Note that the pattern matches are all case-insensitive, and only directory
2235    names are matched, not file names.
2236    
2237  =back  =back
2238    
2239  =cut  =cut
2240    
2241  sub SetPermissions {  sub SetPermissions {
2242      # Get the parameters.      # Get the parameters.
2243      my ($dirName, $group, $mask) = @_;      my ($dirName, $group, $mask, @otherMasks) = @_;
2244      # Set up for error recovery.      # Set up for error recovery.
2245      eval {      eval {
2246            # Switch to the specified directory.
2247          ChDir($dirName);          ChDir($dirName);
2248          # Get the group ID.          # Get the group ID.
2249          my $gid = getgrnam($group);          my $gid = getgrnam($group);
2250          Trace("Fixing permissions for directory $dirName using group $group($gid).") if T(2);          # Get the mask for tracing.
2251            my $traceMask = sprintf("%04o", $mask) . "($mask)";
2252            Trace("Fixing permissions for directory $dirName using group $group($gid) and mask $traceMask.") if T(2);
2253          my $fixCount = 0;          my $fixCount = 0;
2254          my $lookCount = 0;          my $lookCount = 0;
2255          # @dirs will be a stack of directories to be processed.          # @dirs will be a stack of directories to be processed.
# Line 2055  Line 2257 
2257          while (scalar(@dirs) > 0) {          while (scalar(@dirs) > 0) {
2258              # Get the current directory.              # Get the current directory.
2259              my $dir = pop @dirs;              my $dir = pop @dirs;
2260              # Get all its non-hidden members.              # Check for a match to one of the specified directory names. To do
2261                # that, we need to pull the individual part of the name off of the
2262                # whole path.
2263                my $simpleName = $dir;
2264                if ($dir =~ m!/([^/]+)$!) {
2265                    $simpleName = $1;
2266                }
2267                Trace("Simple directory name for $dir is $simpleName.") if T(4);
2268                # Search for a match.
2269                my $match = 0;
2270                my $i;
2271                for ($i = 0; $i < $#otherMasks && ! $match; $i += 2) {
2272                    my $pattern = $otherMasks[$i];
2273                    if ($simpleName =~ /$pattern/i) {
2274                        $match = 1;
2275                    }
2276                }
2277                # Check for a match. Note we use $i-1 because the loop added 2
2278                # before terminating due to the match.
2279                if ($match && $otherMasks[$i-1] != $mask) {
2280                    # This directory matches one of the incoming patterns, and it's
2281                    # a different mask, so we process it recursively with that mask.
2282                    SetPermissions($dir, $group, $otherMasks[$i-1], @otherMasks);
2283                } else {
2284                    # Here we can process normally. Get all of the non-hidden members.
2285              my @submems = OpenDir($dir, 1);              my @submems = OpenDir($dir, 1);
2286              for my $submem (@submems) {              for my $submem (@submems) {
2287                  # Get the full name.                  # Get the full name.
# Line 2063  Line 2289 
2289                  Trace("Checking member $thisMem.") if T(4);                  Trace("Checking member $thisMem.") if T(4);
2290                  $lookCount++;                  $lookCount++;
2291                  if ($lookCount % 1000 == 0) {                  if ($lookCount % 1000 == 0) {
2292                      Trace("$lookCount members examined. Current is $thisMem.") if T(3);                          Trace("$lookCount members examined. Current is $thisMem. Mask is $traceMask") if T(3);
2293                  }                  }
2294                  # Fix the group.                  # Fix the group.
2295                  chown -1, $gid, $thisMem;                  chown -1, $gid, $thisMem;
# Line 2075  Line 2301 
2301                      # and we want to skip it anyway.                      # and we want to skip it anyway.
2302                      if ($fileInfo) {                      if ($fileInfo) {
2303                          my $fileMode = $fileInfo->mode;                          my $fileMode = $fileInfo->mode;
2304                          if (($fileMode & $mask) == 0) {                              if (($fileMode & $mask) != $mask) {
2305                              # Fix this member.                              # Fix this member.
2306                              $fileMode |= $mask;                              $fileMode |= $mask;
2307                              chmod $fileMode, $thisMem;                              chmod $fileMode, $thisMem;
# Line 2089  Line 2315 
2315                  }                  }
2316              }              }
2317          }          }
2318            }
2319          Trace("$lookCount files and directories processed, $fixCount fixed.") if T(2);          Trace("$lookCount files and directories processed, $fixCount fixed.") if T(2);
2320      };      };
2321      # Check for an error.      # Check for an error.

Legend:
Removed from v.1.47  
changed lines
  Added in v.1.61

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3