3 =head1 NAME $RCSfile: Utils.pm,v $
5 Utils - Simple and often used utilities
13 Andrew DeFaria <Andrew@ClearSCM.com>
21 Thu Jan 5 15:15:29 PST 2006
25 $Date: 2013/03/28 21:18:55 $
31 This module seeks to encapsulate useful utilities, things that are often done
32 over and over again but who's classification is miscellaneous.
36 my @children = GetChildren ($pid);
38 my @lines = ReadFile ("/tmp/file");
40 print "Found foo!\n" if InArray ("foo", @bar);
42 my ($status, @output) = Execute ("ps -ef");
46 A collection of utility type subroutines.
50 The following routines are exported:
63 use POSIX qw (setsid);
90 # In case the user hits Ctrl-C
91 print "\nControl-C\n";
98 sub EnterDaemonMode (;$$$) {
99 my ($logfile, $errorlog, $pidfile) = @_;
103 =head2 EnterDaemonMode ($logfile, $errorlog)
105 There is a right way to enter "daemon mode" and this routine is for that. If you
106 call EnterDaemonMode your process will be disassociated from the terminal and
107 enter into a background mode just like a good daemon.
111 =for html <blockquote>
117 File name of where to redirect STDOUT for the daemon (Default: $NULL)
121 File name of where to redirect STDERR for the daemon (Default: $NULL)
125 =for html </blockquote>
129 =for html <blockquote>
137 =for html </blockquote>
146 # Redirect STDIN to $NULL
147 open STDIN, '<', $NULL
148 or error "Can't read $NULL ($!)", 1;
150 # Redirect STDOUT to logfile
151 open STDOUT, '>>', $logfile
152 or error "Can't write to $logfile ($!)", 1;
154 # Redirect STDERR to errorlog
155 open STDERR, '>>', $errorlog
156 or error "Can't write to $errorlog ($!)", 1;
158 # Change the current directory to /
159 my $ROOT = $ARCHITECTURE eq "windows" ? "C:\\" : "/";
161 or error "Can't chdir to $ROOT ($!), 1";
166 # Now fork the daemon
167 defined (my $pid = fork)
168 or error "Can't create daemon ($!)", 1;
170 # Now the parent exits
173 # Write pidfile if specified
175 $pidfile = File::Spec->rel2abs ($pidfile);
177 open $file, '>', $pidfile
178 or warning "Unable to open pidfile $pidfile for writing - $!";
185 # Set process to be session leader
187 or error "Can't start a new session ($!)", 1;
197 =head2 Execute ($command)
199 We all execute OS commands and then have to deal with the output and return
200 codes and the like. How about an easy Execute subroutine. It takes one
201 parameter, the command to execute, executes it and returns two parameters, the
202 output in a nice chomped array and the status.
206 =for html <blockquote>
216 =for html </blockquote>
220 =for html <blockquote>
224 =item A status scalar and an array of lines output from the command (if any).
226 Note, no redirection of STDERR is included. If you want STDERR included in
227 STDOUT then do so in the $command passed in.
231 =for html </blockquote>
235 local $SIG{CHLD} = 'DEFAULT';
242 return ($status, @output);
245 sub GetChildren (;$) {
250 =head2 GetChildren ($pid)
252 Returns an array of children pids for the passed in $pid.
254 NOTE: This assumes that the utility pstree exists and is in the callers PATH.
258 =for html <blockquote>
264 $pid to return the subtree of (Default: pid of init)
268 =for html </blockquote>
272 =for html <blockquote>
276 =item Array of children pids
280 =for html </blockquote>
288 my @output = `pstree -ap $pid`;
290 return @children if $? == 0;
295 # Skip the pstree process and the parent process - we want only
297 next if /pstree/ or /\($pid\)/;
307 sub GetPassword (;$) {
312 =head2 GetPassword (;$prompt)
314 Prompt for a password
318 =for html <blockquote>
324 Prompt string to use (Default: "Password:")
328 =for html </blockquote>
332 =for html <blockquote>
340 =for html </blockquote>
345 $prompt ||= 'Password';
353 $SIG{INT} = \&_restoreTerm;
360 while (not defined ($key = ReadKey -1)) { }
362 if ($key =~ /(\r|\n)/) {
373 ReadMode 'restore'; # Reset tty mode before exiting.
375 $SIG{INT} = 'DEFAULT';
381 my ($item, @array) = @_;
385 =head2 InArray ($item, @array)
387 Find an item in an array.
391 =for html <blockquote>
405 =for html </blockquote>
409 =for html <blockquote>
413 =item $TRUE if found - $FALSE otherwise
417 =for html </blockquote>
422 return $TRUE if $item eq $_;
434 Return an array of the 1, 5, and 15 minute load averages.
438 =for html <blockquote>
446 =for html </blockquote>
450 =for html <blockquote>
454 =item An array of the 1, 5, and 15 minute load averages in a list context.
455 In a scalar context just the 1 minute load average.
459 =for html </blockquote>
463 # TODO: Make it work on Windows...
464 return if $^O =~ /win/i;
466 open my $loadAvg, '/proc/loadavg'
467 or croak "Unable to open /proc/loadavg\n";
469 my $load = <$loadAvg>;
473 my @loadAvgs = split /\s/, $load;
478 return $loadAvgs[0]; # This is the 1 minute average
484 sub StartPipe ($;$) {
485 my ($to, $existingPipe) = @_;
489 =head2 StartPipe ($to, $existingPipe)
495 =for html <blockquote>
501 String representing the other end of the pipe
505 Already existing pipe handle (from a previous call to StartPipe)
509 =for html </blockquote>
513 =for html <blockquote>
517 =item A $pipe to used for PipeOutput
521 =for html </blockquote>
528 open $existingPipe, '|-', $to
529 or error "Unable to open pipe - $!", 1;
531 return $existingPipe;
533 open $pipe, '|-', $to
534 or error "Unable to open pipe - $!", 1;
540 sub PipeOutputArray ($@) {
541 my ($to, @output) = @_;
545 =head2 PipeOutputArray ($to, @ouput)
551 =for html <blockquote>
557 String representing the other end of the pipe to pipe @output to
565 =for html </blockquote>
569 =for html <blockquote>
577 =for html </blockquote>
581 open my $pipe, '|', $to
582 or error "Unable to open pipe - $!", 1;
593 sub PipeOutput ($;$) {
594 my ($line, $topipe) = @_;
598 =head2 PipeOutput ($line, $topipe)
600 Pipes a single line to $topipe
604 =for html <blockquote>
610 Line to output to $topipe.
614 A pipe returned by StartPipe (or our $pipe) to which the $line is piped.
618 =for html </blockquote>
622 =for html <blockquote>
630 =for html </blockquote>
636 chomp $line; chop $line if $line =~ /\r$/;
638 print $pipe "$line\n";
644 my ($pipeToStop) = @_;
648 =head2 StopPipe ($pipe)
654 =for html <blockquote>
664 =for html </blockquote>
668 =for html <blockquote>
676 =for html </blockquote>
680 $pipeToStop ||= $pipe;
682 close $pipeToStop if $pipeToStop;
692 =head2 PageOutput (@ouput)
694 Pages output to the screen
698 =for html <blockquote>
708 =for html </blockquote>
712 =for html <blockquote>
720 =for html </blockquote>
725 PipeOutputArray $ENV{PAGER}, @output;
734 sub RedirectOutput ($$@) {
735 my ($to, $mode, @output) = @_;
739 =head2 RedirectOutput ($to, @ouput)
741 Pages output to the screen
745 =for html <blockquote>
751 Where to send the output
759 =for html </blockquote>
763 =for html <blockquote>
771 =for html </blockquote>
775 croak 'Mode must be > or >>'
776 unless ($mode eq '>' or $mode eq '>>');
778 open my $out, $mode, $to
779 or croak "Unable to open $to for writing - $!";
794 =head2 ReadFile ($filename)
796 How many times have you coded a Perl subroutine, or just staight inline Perl to
797 open a file, read all the lines into an array and close the file. This routine
798 does that very thing along with the associated and proper checking of open
799 failure and even trims the lines in the output array of trailing newlines? This
800 routine returns an array of the lines in the filename passed in.
804 =for html <blockquote>
814 =for html </blockquote>
818 =for html <blockquote>
822 =item Array of lines in the file
826 =for html </blockquote>
830 open my $file, '<', $filename
831 or error "Unable to open $filename ($!)", 1;
839 or error "Unable to close $filename ($!)", 1;
846 push @cleansed_lines, $_ if !/^#/; # Discard comment lines
849 return @cleansed_lines;
858 my ($total, $log) = @_;
862 =head2 Stats ($total, $log)
864 Reports runtime stats
868 =for html <blockquote>
874 Reference to a hash of total counters. The keys of the hash will be the labels
875 and the values of the hash will be the counters.
879 Logger object to log stats to (if specified). Note: if the Logger object has
880 errors or warnings then they will be automatically included in the output.
884 =for html </blockquote>
888 =for html <blockquote>
896 =for html </blockquote>
900 my $msg = "$FindBin::Script Run Statistics:";
902 if ($log and ref $log eq 'Logger') {
903 $total->{errors} = $log->{errors};
904 $total->{warnings} = $log->{warnings};
908 # Display statistics (if any)
915 foreach (sort keys %$total) {
916 $msg = $total->{$_} . "\t $_";
919 $log->msg ($total->{$_} . "\t $_");
936 Reports usage using perldoc
940 =for html <blockquote>
946 Message to output before doing perldoc
950 =for html </blockquote>
954 =for html <blockquote>
958 =item Does not return
962 =for html </blockquote>
980 =head1 CONFIGURATION AND ENVIRONMENT
988 L<File::Spec|File::Spec>
994 =head2 ClearSCM Perl Modules
996 =for html <p><a href="/php/scm_man.php?file=lib/Display.pm">Display</a></p>
998 =for html <p><a href="/php/scm_man.php?file=lib/Logger.pm">Logger</a></p>
1000 =for html <p><a href="/php/scm_man.php?file=lib/OSDep.pm">OSDep</a></p>
1002 =head1 INCOMPATABILITIES
1006 =head1 BUGS AND LIMITATIONS
1008 There are no known bugs in this module.
1010 Please report problems to Andrew DeFaria <Andrew@ClearSCM.com>.
1012 =head1 LICENSE AND COPYRIGHT
1014 This Perl Module is freely available; you can redistribute it and/or modify it
1015 under the terms of the GNU General Public License as published by the Free
1016 Software Foundation; either version 2 of the License, or (at your option) any
1019 This Perl Module is distributed in the hope that it will be useful, but WITHOUT
1020 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
1021 FOR A PARTICULAR PURPOSE. See the GNU General Public License
1022 (L<http://www.gnu.org/copyleft/gpl.html>) for more details.
1024 You should have received a copy of the GNU General Public License along with
1025 this Perl Module; if not, write to the Free Software Foundation, Inc., 59
1026 Temple Place - Suite 330, Boston, MA 02111-1307, USA. reserved.