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 (;$) {
317 =head2 GetPassword (;$prompt)
319 Prompt for a password
323 =for html <blockquote>
329 Prompt string to use (Default: "Password:")
333 =for html </blockquote>
337 =for html <blockquote>
345 =for html </blockquote>
349 $prompt ||= 'Password';
357 $SIG{INT} = \&_restoreTerm;
364 while (not defined ($key = ReadKey -1)) { }
366 if ($key =~ /(\r|\n)/) {
377 ReadMode 'restore'; # Reset tty mode before exiting.
379 $SIG{INT} = 'DEFAULT';
385 my ($item, @array) = @_;
389 =head2 InArray ($item, @array)
391 Find an item in an array.
395 =for html <blockquote>
409 =for html </blockquote>
413 =for html <blockquote>
417 =item $TRUE if found - $FALSE otherwise
421 =for html </blockquote>
426 return $TRUE if $item eq $_;
434 sub StartPipe ($;$) {
435 my ($to, $existingPipe) = @_;
439 =head2 StartPipe ($to, $existingPipe)
445 =for html <blockquote>
451 String representing the other end of the pipe
455 Already existing pipe handle (from a previous call to StartPipe)
459 =for html </blockquote>
463 =for html <blockquote>
467 =item A $pipe to used for PipeOutput
471 =for html </blockquote>
478 open $existingPipe, '|-', $to
479 or error "Unable to open pipe - $!", 1;
481 return $existingPipe;
483 open $pipe, '|-', $to
484 or error "Unable to open pipe - $!", 1;
490 sub PipeOutputArray ($@) {
491 my ($to, @output) = @_;
495 =head2 PipeOutputArray ($to, @ouput)
501 =for html <blockquote>
507 String representing the other end of the pipe to pipe @output to
515 =for html </blockquote>
519 =for html <blockquote>
527 =for html </blockquote>
531 open my $pipe, '|', $to
532 or error "Unable to open pipe - $!", 1;
543 sub PipeOutput ($;$) {
544 my ($line, $topipe) = @_;
548 =head2 PipeOutput ($line, $topipe)
550 Pipes a single line to $topipe
554 =for html <blockquote>
560 Line to output to $topipe.
564 A pipe returned by StartPipe (or our $pipe) to which the $line is piped.
568 =for html </blockquote>
572 =for html <blockquote>
580 =for html </blockquote>
586 chomp $line; chop $line if $line =~ /\r$/;
588 print $pipe "$line\n";
594 my ($pipeToStop) = @_;
598 =head2 StopPipe ($pipe)
604 =for html <blockquote>
614 =for html </blockquote>
618 =for html <blockquote>
626 =for html </blockquote>
630 $pipeToStop ||= $pipe;
632 close $pipeToStop if $pipeToStop;
642 =head2 PageOutput (@ouput)
644 Pages output to the screen
648 =for html <blockquote>
658 =for html </blockquote>
662 =for html <blockquote>
670 =for html </blockquote>
675 PipeOutputArray $ENV{PAGER}, @output;
684 sub RedirectOutput ($$@) {
685 my ($to, $mode, @output) = @_;
689 =head2 RedirectOutput ($to, @ouput)
691 Pages output to the screen
695 =for html <blockquote>
701 Where to send the output
709 =for html </blockquote>
713 =for html <blockquote>
721 =for html </blockquote>
725 croak 'Mode must be > or >>'
726 unless ($mode eq '>' or $mode eq '>>');
728 open my $out, $mode, $to
729 or croak "Unable to open $to for writing - $!";
744 =head2 ReadFile ($filename)
746 How many times have you coded a Perl subroutine, or just staight inline Perl to
747 open a file, read all the lines into an array and close the file. This routine
748 does that very thing along with the associated and proper checking of open
749 failure and even trims the lines in the output array of trailing newlines? This
750 routine returns an array of the lines in the filename passed in.
754 =for html <blockquote>
764 =for html </blockquote>
768 =for html <blockquote>
772 =item Array of lines in the file
776 =for html </blockquote>
780 open my $file, '<', $filename
781 or error "Unable to open $filename ($!)", 1;
789 or error "Unable to close $filename ($!)", 1;
796 push @cleansed_lines, $_ if !/^#/; # Discard comment lines
799 return @cleansed_lines;
808 my ($total, $log) = @_;
812 =head2 Stats ($total, $log)
814 Reports runtime stats
818 =for html <blockquote>
824 Reference to a hash of total counters. The keys of the hash will be the labels
825 and the values of the hash will be the counters.
829 Logger object to log stats to (if specified)
833 =for html </blockquote>
837 =for html <blockquote>
845 =for html </blockquote>
849 my $msg = "$FindBin::Script Run Statistics:";
851 if (scalar keys %$total) {
852 # Display statistics (if any)
859 foreach (sort keys %$total) {
860 $msg = $$total{$_} . "\t $_";
863 $log->msg ($$total{$_} . "\t $_");
880 Reports usage using perldoc
884 =for html <blockquote>
890 Message to output before doing perldoc
894 =for html </blockquote>
898 =for html <blockquote>
902 =item Does not return
906 =for html </blockquote>
924 =head1 CONFIGURATION AND ENVIRONMENT
932 L<File::Spec|File::Spec>
940 =head2 ClearSCM Perl Modules
942 =for html <p><a href="/php/scm_man.php?file=lib/Display.pm">Display</a></p>
944 =for html <p><a href="/php/scm_man.php?file=lib/Logger.pm">Logger</a></p>
946 =for html <p><a href="/php/scm_man.php?file=lib/OSDep.pm">OSDep</a></p>
948 =head1 INCOMPATABILITIES
952 =head1 BUGS AND LIMITATIONS
954 There are no known bugs in this module.
956 Please report problems to Andrew DeFaria <Andrew@ClearSCM.com>.
958 =head1 LICENSE AND COPYRIGHT
960 This Perl Module is freely available; you can redistribute it and/or modify it
961 under the terms of the GNU General Public License as published by the Free
962 Software Foundation; either version 2 of the License, or (at your option) any
965 This Perl Module is distributed in the hope that it will be useful, but WITHOUT
966 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
967 FOR A PARTICULAR PURPOSE. See the GNU General Public License
968 (L<http://www.gnu.org/copyleft/gpl.html>) for more details.
970 You should have received a copy of the GNU General Public License along with
971 this Perl Module; if not, write to the Free Software Foundation, Inc., 59
972 Temple Place - Suite 330, Boston, MA 02111-1307, USA. reserved.