1 package Maasha::Common;
4 # Copyright (C) 2006-2007 Martin A. Hansen.
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; either version 2
9 # of the License, or (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 # http://www.gnu.org/copyleft/gpl.html
23 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
26 # This module contains commonly used routines
29 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
37 use Time::HiRes qw( gettimeofday );
42 use vars qw( @ISA @EXPORT @EXPORT_OK );
44 @ISA = qw( Exporter ) ;
46 use Inline ( C => <<'END_C', DIRECTORY => $ENV{ "BP_TMP" } );
48 int index_m( char *str, char *substr, size_t str_len, size_t substr_len, size_t offset, size_t max_mismatch )
50 /* Martin A. Hansen & Selene Fernandez, August 2008 */
52 /* Locates a substring within a string starting from offset and allowing for max_mismatch mismatches. */
53 /* The begin position of the substring is returned if found otherwise -1 is returned. */
58 size_t max_match = substr_len - max_mismatch;
62 while ( i < str_len - ( max_match + max_mismatch ) + 1 )
66 while ( j < substr_len - ( max_match + max_mismatch ) + 1 )
68 if ( match_m( str, substr, str_len, substr_len, i, j, max_match, max_mismatch ) != 0 ) {
82 int match_m( char *str, char *substr, size_t str_len, size_t substr_len, size_t str_offset, size_t substr_offset, size_t max_match, size_t max_mismatch )
84 /* Martin A. Hansen & Selene Fernandez, August 2008 */
86 /* Compares a string and substring starting at speficied string and substring offset */
87 /* positions allowing for a specified number of mismatches. Returns 1 if there is a */
88 /* match otherwise returns 0. */
93 while ( str_offset <= str_len && substr_offset <= substr_len )
95 if ( str[ str_offset ] == substr[ substr_offset ] )
99 if ( match >= max_match ) {
107 if ( mismatch > max_mismatch ) {
124 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
129 # Martin A. Hansen, February 2008.
131 # Print error message and exit with stack trace.
133 my ( $msg, # Error message.
134 $no_stack, # disable stack trace - OPTIONAL
139 my ( $script, $error, @lines, $line, $routine, $file, $line_no, @table, $routine_max, $file_max, $line_max );
143 $script = get_scriptname();
145 $error = Carp::longmess();
147 @lines = split "\n", $error;
149 $line = shift @lines;
151 push @table, [ "Routine", "File", "Line" ];
152 push @table, [ "-------", "----", "----" ];
154 $routine_max = length "Routine";
155 $file_max = length "File";
156 $line_max = length "Line";
158 if ( $line =~ /^ at (.+) line (\d+)$/ )
163 $file_max = length $file if length $file > $file_max;
164 $line_max = length $line_no if length $line_no > $line_max;
166 push @table, [ "", $file, $line_no ];
170 die qq(ERROR: Unrecognized error line "$line"\n);
173 foreach $line ( @lines )
175 if ( $line =~ /^\s*(.+) called at (.+) line (\d+)\s*$/ )
181 $routine =~ s/\(.+\)$/ .../;
183 $routine_max = length $routine if length $routine > $routine_max;
184 $file_max = length $file if length $file > $file_max;
185 $line_max = length $line_no if length $line_no > $line_max;
187 push @table, [ $routine, $file, $line_no ];
191 die qq(ERROR: Unrecognized error line "$line"\n);
197 print STDERR qq(\nERROR!\n\nProgram \'$script\' failed: $msg.\n\n);
199 die( "MAASHA_ERROR" ) if $no_stack;
205 foreach $line ( @table ) {
206 printf( STDERR "%-${routine_max}s%-${file_max}s%s\n", @{ $line } );
211 die( "MAASHA_ERROR" );
217 # Martin A. Hansen, January 2004.
219 # Read opens a file and returns a filehandle.
221 my ( $path, # full path to file
228 $type = `file $path` if -f $path;
230 if ( $type =~ /gzip compressed/ ) {
231 $fh = new IO::File "zcat $path|" or Maasha::Common::error( qq(Could not read-open file "$path": $!) );
233 $fh = new IO::File $path, "r" or Maasha::Common::error( qq(Could not read-open file "$path": $!) );
242 # Martin A. Hansen, January 2004.
244 # write opens a file and returns a filehandle
246 my ( $path, # full path to file
247 $gzip, # flag if data is to be gzipped - OPRIONAL
255 $fh = new IO::File "|gzip -f>$path" or Maasha::Common::error( qq(Could not write-open file "$path": $!) );
257 $fh = new IO::File $path, "w" or Maasha::Common::error( qq(Could not write-open file "$path": $!) );
266 # Martin A. Hansen, February 2006.
268 # append opens file and returns a filehandle
270 my ( $path, # path to file
277 $fh = new IO::File $path, "a" or Maasha::Common::error( qq(Could not append-open file "$path": $!) );
285 # Martin A. Hansen, January 2007.
287 # opens a pipe and returns a filehandle
291 $fh = new IO::File "-" or Maasha::Common::error( qq(Could not open pipe: $!) );
299 # Martin A. Hansen, December 2006
301 # reads arguments from @ARGV which is strictly formatted.
302 # three kind of argments are accepted:
303 # 1) file names [filename]
304 # 2) options with value [--option=value]
305 # 3) option without value [--option]
307 my ( $args, # list of arguments
308 $ok_args, # list of accepted arguments - OPTIONAL
313 my ( %ok_hash, $arg, @dirs, @files, %hash );
315 foreach $arg ( @{ $args } )
317 if ( $arg =~ /^--([^=]+)=(.+)$/ ) {
319 } elsif ( $arg =~ /^--(.+)$/ ) {
321 } elsif ( -d $arg ) {
323 } elsif ( -f $arg ) {
326 Maasha::Common::error( qq(Bad syntax in argument->"$arg") );
330 $hash{ "DIRS" } = \@dirs;
331 $hash{ "FILES" } = \@files;
335 map { $ok_hash{ $_ } = 1 } @{ $ok_args };
337 $ok_hash{ "DIRS" } = 1;
338 $ok_hash{ "FILES" } = 1;
340 map { Maasha::Common::error( qq(Unknown argument->"$_") ) if not exists $ok_hash{ $_ } } keys %hash;
343 return wantarray ? %hash : \%hash;
349 # Martin A. Hansen, July 2008.
351 # Get current time as a number.
361 # Martin A. Hansen, May 2008.
363 # Get current time in high resolution.
367 return gettimeofday();
373 # Martin A. Hansen, July 2008.
375 # Get process id for current process.
385 # Martin A. Hansen, April 2008.
387 # Create a session id based on time and pid.
391 return get_time . get_processid;
397 # Martin A. Hansen, July 2008.
399 # Return the user name of the current user.
403 return $ENV{ 'USER' };
409 # Martin A. Hansen, April 2008.
411 # Create a temporary directory based on
412 # $ENV{ 'BP_TMP' } and sessionid.
414 # this thing is a really bad solution and needs to be removed.
418 my ( $user, $sid, $pid, $path );
420 Maasha::Common::error( qq(no BP_TMP set in %ENV) ) if not -d $ENV{ 'BP_TMP' };
422 $user = Maasha::Common::get_user();
423 $sid = Maasha::Common::get_sessionid();
424 $pid = Maasha::Common::get_processid();
426 $path = "$ENV{ 'BP_TMP' }/" . join( "_", $user, $sid, $pid, "bp_tmp" );
428 Maasha::Filesys::dir_create( $path );
436 # Martin A. Hansen, February 2007
438 # returns the script name
440 return ( split "/", $0 )[ -1 ];
446 # Martin A. Hansen, February 2007
448 # Given a full path to a file returns the basename,
449 # which is the part of the name before the last '.'.
451 my ( $path, # full path to filename
456 $basename = ( split "/", $path )[ -1 ];
458 $basename =~ s/(.+)\.?.*/$1/;
466 # Martin A. Hansen, July 2008.
468 # Given a filehandle to a file gets the
469 # next line which is split into a list of
470 # fields that is returned.
472 my ( $fh, # filehandle
473 $delimiter, # field seperator - OPTIONAL
478 my ( $line, @fields );
482 return if not defined $line;
488 @fields = split "$delimiter", $line;
490 return wantarray ? @fields : \@fields;
496 # Martin A. Hansen, April 2007.
498 # Run an execute with optional arguments.
500 my ( $exe, # executable to run
501 $args, # argument string
507 my ( $command_line, $result );
509 $command_line = Maasha::Config::get_exe( $exe );
510 $command_line .= " " . $args if $args;
511 $command_line = "nice -n19 " . $command_line if $nice;
513 system( $command_line ) == 0 or Maasha::Common::error( qq(Could not execute "$command_line": $?) );
519 # Martin A. Hansen, April 2008.
521 # Run an execute with optional arguments returning the output
524 my ( $exe, # executable to run
525 $args, # argument string
531 my ( $command_line, @result );
533 $command_line = Maasha::Config::get_exe( $exe );
534 $command_line .= " " . $args if $args;
535 $command_line = "nice -n19 " . $command_line if $nice;
537 @result = `$command_line`;
541 return wantarray ? @result : \@result;
547 # Martin A. Hansen, February 2006.
549 # returns timestamp for use in log file.
550 # format: YYYY-MM-DD HH:MM:SS
554 my ( $year, $mon, $day, $time );
556 ( undef, undef, undef, $day, $mon, $year, undef, undef ) = gmtime( time );
558 $mon += 1; # first month is 0, so we correct accordingly
561 $day = sprintf "%02d", $day;
562 $mon = sprintf "%02d", $mon;
566 $time =~ s/.*(\d{2}:\d{2}:\d{2}).*/$1/;
568 return "$year-$mon-$day $time";
574 # Martin A. Hansen, June 2009.
576 # Return the difference between two time stamps in
577 # the time stamp format.
579 my ( $t0, # time stamp 0
583 # Returns a time stamp string.
585 my ( $year0, $mon0, $day0, $hour0, $min0, $sec0,
586 $year1, $mon1, $day1, $hour1, $min1, $sec1,
587 $year, $mon, $day, $hour, $min, $sec );
589 $t0 =~ /(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)/;
597 $sec0 += $day0 * 24 * 60 * 60;
598 $sec0 += $hour0 * 60 * 60;;
601 $t1 =~ /(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)/;
609 $sec1 += $day1 * 24 * 60 * 60;
610 $sec1 += $hour1 * 60 * 60;;
613 $year = $year1 - $year0;
614 $mon = $mon1 - $mon0;
615 $day = $day1 - $day0;
617 $sec = $sec1 - $sec0;
619 $hour = int( $sec / ( 60 * 60 ) );
620 $sec -= $hour * 60 * 60;
622 $min = int( $sec / 60 );
625 return join( ":", sprintf( "%02d", $hour ), sprintf( "%02d", $min ), sprintf( "%02d", $sec ) );
631 # Martin A. Hansen, July 2008.
633 # Given a process ID check if it is running
634 # on the system. Return 1 if the process is
637 my ( $pid, # process ID to check.
644 @ps_table = run_and_return( "ps", " a" );
646 if ( grep /^\s*$pid\s+/, @ps_table ) {
656 # Martin A. Hansen, May 2005
658 # Takes a given line and wraps it to a given width,
659 # without breaking any words.
661 my ( $line, # line to wrap
665 # Returns a list of lines.
667 my ( @lines, $substr, $wrap_pos, $pos, $new_line );
671 while ( $pos < length $line )
673 $substr = substr $line, $pos, $width;
675 if ( length $substr == $width )
677 $substr = reverse $substr;
678 $wrap_pos = index $substr, " ";
680 $new_line = substr $line, $pos, $width - $wrap_pos;
683 $pos += $width - $wrap_pos;
692 push @lines, $new_line;
695 return wantarray ? @lines : \@lines;
699 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<