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);
89 # In case the user hits Ctrl-C
90 print "\nControl-C\n";
97 sub EnterDaemonMode (;$$$) {
98 my ($logfile, $errorlog, $pidfile) = @_;
102 =head2 EnterDaemonMode ($logfile, $errorlog)
104 There is a right way to enter "daemon mode" and this routine is for that. If you
105 call EnterDaemonMode your process will be disassociated from the terminal and
106 enter into a background mode just like a good daemon.
110 =for html <blockquote>
116 File name of where to redirect STDOUT for the daemon (Default: $NULL)
120 File name of where to redirect STDERR for the daemon (Default: $NULL)
124 =for html </blockquote>
128 =for html <blockquote>
136 =for html </blockquote>
145 # Redirect STDIN to $NULL
146 open STDIN, '<', $NULL
147 or error "Can't read $NULL ($!)", 1;
149 # Redirect STDOUT to logfile
150 open STDOUT, '>>', $logfile
151 or error "Can't write to $logfile ($!)", 1;
153 # Redirect STDERR to errorlog
154 open STDERR, '>>', $errorlog
155 or error "Can't write to $errorlog ($!)", 1;
157 # Change the current directory to /
158 my $ROOT = $ARCH eq "windows" ? "C:\\" : "/";
160 or error "Can't chdir to $ROOT ($!), 1";
165 # Now fork the daemon
166 defined (my $pid = fork)
167 or error "Can't create daemon ($!)", 1;
169 # Now the parent exits
172 # Write pidfile if specified
174 $pidfile = File::Spec->rel2abs ($pidfile);
176 open $file, '>', $pidfile
177 or warning "Unable to open pidfile $pidfile for writing - $!";
184 # Set process to be session leader
186 or error "Can't start a new session ($!)", 1;
196 =head2 Execute ($command)
198 We all execute OS commands and then have to deal with the output and return
199 codes and the like. How about an easy Execute subroutine. It takes one
200 parameter, the command to execute, executes it and returns two parameters, the
201 output in a nice chomped array and the status.
205 =for html <blockquote>
215 =for html </blockquote>
219 =for html <blockquote>
223 =item A status scalar and an array of lines output from the command (if any).
225 Note, no redirection of STDERR is included. If you want STDERR included in
226 STDOUT then do so in the $command passed in.
230 =for html </blockquote>
234 # Save $SIG{CHLD} so we can set it to 'DEFAULT' and then restore it later.
235 # Helps when you are doing process handling.
236 my $sigchld = $SIG{CHLD};
238 local $SIG{CHLD} = 'DEFAULT';
243 local $SIG{CHLD} = $sigchld;
247 return ($status, @output);
250 sub GetChildren (;$) {
255 =head2 GetChildren ($pid)
257 Returns an array of children pids for the passed in $pid.
259 NOTE: This assumes that the utility pstree exists and is in the callers PATH.
263 =for html <blockquote>
269 $pid to return the subtree of (Default: pid of init)
273 =for html </blockquote>
277 =for html <blockquote>
281 =item Array of children pids
285 =for html </blockquote>
293 my @output = `pstree -ap $pid`;
295 return @children if $? == 0;
300 # Skip the pstree process and the parent process - we want only
302 next if /pstree/ or /\($pid\)/;
312 sub GetPassword (;$) {
315 $prompt ||= 'Password';
323 $SIG{INT} = \&_restoreTerm;
330 while (not defined ($key = ReadKey -1)) { }
332 if ($key =~ /(\r|\n)/) {
343 ReadMode 'restore'; # Reset tty mode before exiting.
345 $SIG{INT} = 'DEFAULT';
351 my ($item, @array) = @_;
355 =head2 InArray ($item, @array)
357 Find an item in an array.
361 =for html <blockquote>
375 =for html </blockquote>
379 =for html <blockquote>
383 =item $TRUE if found - $FALSE otherwise
387 =for html </blockquote>
392 return $TRUE if $item eq $_;
400 sub StartPipe ($;$) {
401 my ($to, $existingPipe) = @_;
405 =head2 StartPipe ($to, $existingPipe)
411 =for html <blockquote>
417 String representing the other end of the pipe
421 Already existing pipe handle (from a previous call to StartPipe)
425 =for html </blockquote>
429 =for html <blockquote>
433 =item A $pipe to used for PipeOutput
437 =for html </blockquote>
444 open $existingPipe, '|-', $to
445 or error "Unable to open pipe - $!", 1;
447 return $existingPipe;
449 open $pipe, '|-', $to
450 or error "Unable to open pipe - $!", 1;
456 sub PipeOutputArray ($@) {
457 my ($to, @output) = @_;
461 =head2 PipeOutputArray ($to, @ouput)
467 =for html <blockquote>
473 String representing the other end of the pipe to pipe @output to
481 =for html </blockquote>
485 =for html <blockquote>
493 =for html </blockquote>
497 open my $pipe, '|', $to
498 or error "Unable to open pipe - $!", 1;
509 sub PipeOutput ($;$) {
510 my ($line, $topipe) = @_;
514 =head2 PipeOutput ($line, $topipe)
516 Pipes a single line to $topipe
520 =for html <blockquote>
526 Line to output to $topipe.
530 A pipe returned by StartPipe (or our $pipe) to which the $line is piped.
534 =for html </blockquote>
538 =for html <blockquote>
546 =for html </blockquote>
552 chomp $line; chop $line if $line =~ /\r$/;
554 print $pipe "$line\n";
560 my ($pipeToStop) = @_;
564 =head2 StopPipe ($pipe)
570 =for html <blockquote>
580 =for html </blockquote>
584 =for html <blockquote>
592 =for html </blockquote>
596 $pipeToStop ||= $pipe;
598 close $pipeToStop if $pipeToStop;
608 =head2 PageOutput (@ouput)
610 Pages output to the screen
614 =for html <blockquote>
624 =for html </blockquote>
628 =for html <blockquote>
636 =for html </blockquote>
641 PipeOutputArray $ENV{PAGER}, @output;
650 sub RedirectOutput ($$@) {
651 my ($to, $mode, @output) = @_;
655 =head2 RedirectOutput ($to, @ouput)
657 Pages output to the screen
661 =for html <blockquote>
667 Where to send the output
675 =for html </blockquote>
679 =for html <blockquote>
687 =for html </blockquote>
691 croak 'Mode must be > or >>'
692 unless ($mode eq '>' or $mode eq '>>');
694 open my $out, $mode, $to
695 or croak "Unable to open $to for writing - $!";
710 =head2 ReadFile ($filename)
712 How many times have you coded a Perl subroutine, or just staight inline Perl to
713 open a file, read all the lines into an array and close the file. This routine
714 does that very thing along with the associated and proper checking of open
715 failure and even trims the lines in the output array of trailing newlines? This
716 routine returns an array of the lines in the filename passed in.
720 =for html <blockquote>
730 =for html </blockquote>
734 =for html <blockquote>
738 =item Array of lines in the file
742 =for html </blockquote>
746 open my $file, '<', $filename
747 or error "Unable to open $filename ($!)", 1;
755 or error "Unable to close $filename ($!)", 1;
762 push @cleansed_lines, $_ if !/^#/; # Discard comment lines
765 return @cleansed_lines;
774 my ($total, $log) = @_;
778 =head2 Stats ($total, $log)
780 Reports runtime stats
784 =for html <blockquote>
790 Reference to a hash of total counters. The keys of the hash will be the labels
791 and the values of the hash will be the counters.
795 Logger object to log stats to (if specified)
799 =for html </blockquote>
803 =for html <blockquote>
811 =for html </blockquote>
815 my $msg = "$FindBin::Script Run Statistics:";
817 if (scalar keys %$total) {
818 # Display statistics (if any)
825 foreach (sort keys %$total) {
826 $msg = $$total{$_} . "\t $_";
829 $log->msg ($$total{$_} . "\t $_");
846 Reports usage using perldoc
850 =for html <blockquote>
856 Message to output before doing perldoc
860 =for html </blockquote>
864 =for html <blockquote>
868 =item Does not return
872 =for html </blockquote>
890 =head1 CONFIGURATION AND ENVIRONMENT
898 L<File::Spec|File::Spec>
904 =head2 ClearSCM Perl Modules
906 =for html <p><a href="/php/scm_man.php?file=lib/Display.pm">Display</a></p>
908 =for html <p><a href="/php/scm_man.php?file=lib/Logger.pm">Logger</a></p>
910 =for html <p><a href="/php/scm_man.php?file=lib/OSDep.pm">OSDep</a></p>
912 =head1 INCOMPATABILITIES
916 =head1 BUGS AND LIMITATIONS
918 There are no known bugs in this module.
920 Please report problems to Andrew DeFaria <Andrew@ClearSCM.com>.
922 =head1 LICENSE AND COPYRIGHT
924 This Perl Module is freely available; you can redistribute it and/or modify it
925 under the terms of the GNU General Public License as published by the Free
926 Software Foundation; either version 2 of the License, or (at your option) any
929 This Perl Module is distributed in the hope that it will be useful, but WITHOUT
930 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
931 FOR A PARTICULAR PURPOSE. See the GNU General Public License
932 (L<http://www.gnu.org/copyleft/gpl.html>) for more details.
934 You should have received a copy of the GNU General Public License along with
935 this Perl Module; if not, write to the Free Software Foundation, Inc., 59
936 Temple Place - Suite 330, Boston, MA 02111-1307, USA. reserved.