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, May 2009.
244 # Cats a number of files and returns a filehandle.
246 my ( $files, # full path to file
251 my ( $file, $fh, $type, %type_hash, $file_string );
253 foreach $file ( @{ $files } )
255 Maasha::Common::error( qq(No such file: $file) ) if not -f $file;
257 $type = `file $file`;
259 if ( $type =~ /gzip compressed/ ) {
260 $type_hash{ 'gzip' } = 1;
262 $type_hash{ 'ascii' } = 1;
266 Maasha::Common::error( qq(Mixture of zipped and unzipped files) ) if scalar keys %type_hash > 1;
268 $file_string = join " ", @{ $files };
270 if ( $type =~ /gzip compressed/ ) {
271 $fh = new IO::File "zcat $file_string|" or Maasha::Common::error( qq(Could not open pipe: $!) );
273 $fh = new IO::File "cat $file_string|" or Maasha::Common::error( qq(Could not open pipe: $!) );
282 # Martin A. Hansen, January 2004.
284 # write opens a file and returns a filehandle
286 my ( $path, # full path to file
287 $gzip, # flag if data is to be gzipped - OPRIONAL
295 $fh = new IO::File "|gzip -f>$path" or Maasha::Common::error( qq(Could not write-open file "$path": $!) );
297 $fh = new IO::File $path, "w" or Maasha::Common::error( qq(Could not write-open file "$path": $!) );
306 # Martin A. Hansen, February 2006.
308 # append opens file and returns a filehandle
310 my ( $path, # path to file
317 $fh = new IO::File $path, "a" or Maasha::Common::error( qq(Could not append-open file "$path": $!) );
325 # Martin A. Hansen, January 2007.
327 # opens a pipe and returns a filehandle
331 $fh = new IO::File "-" or Maasha::Common::error( qq(Could not open pipe: $!) );
339 # Martin A. Hansen, December 2004.
341 # writes a data structure to file.
343 my ( $path, # full path to file
344 $data, # data structure
347 Storable::store( $data, $path ) or Maasha::Common::error( qq(Could not write-open file "$path": $!) );
353 # Martin A. Hansen, December 2004.
355 # retrieves hash data structure
356 # (this routines needs to test if its a hash, array or else)
358 my ( $path, # full path to data file
363 $data = Storable::retrieve( $path ) or Maasha::Common::error( qq(Could not read-open file "$path": $!) );
365 return wantarray ? %{ $data } : $data;
371 # Martin A. Hansen, December 2006
373 # reads arguments from @ARGV which is strictly formatted.
374 # three kind of argments are accepted:
375 # 1) file names [filename]
376 # 2) options with value [--option=value]
377 # 3) option without value [--option]
379 my ( $args, # list of arguments
380 $ok_args, # list of accepted arguments - OPTIONAL
385 my ( %ok_hash, $arg, @dirs, @files, %hash );
387 foreach $arg ( @{ $args } )
389 if ( $arg =~ /^--([^=]+)=(.+)$/ ) {
391 } elsif ( $arg =~ /^--(.+)$/ ) {
393 } elsif ( -d $arg ) {
395 } elsif ( -f $arg ) {
398 Maasha::Common::error( qq(Bad syntax in argument->"$arg") );
402 $hash{ "DIRS" } = \@dirs;
403 $hash{ "FILES" } = \@files;
407 map { $ok_hash{ $_ } = 1 } @{ $ok_args };
409 $ok_hash{ "DIRS" } = 1;
410 $ok_hash{ "FILES" } = 1;
412 map { Maasha::Common::error( qq(Unknown argument->"$_") ) if not exists $ok_hash{ $_ } } keys %hash;
415 return wantarray ? %hash : \%hash;
421 # Martin A. Hansen, July 2008.
423 # Get current time as a number.
433 # Martin A. Hansen, May 2008.
435 # Get current time in high resolution.
439 return gettimeofday();
445 # Martin A. Hansen, July 2008.
447 # Get process id for current process.
457 # Martin A. Hansen, April 2008.
459 # Create a session id based on time and pid.
463 return get_time . get_processid;
469 # Martin A. Hansen, July 2008.
471 # Return the user name of the current user.
475 return $ENV{ 'USER' };
481 # Martin A. Hansen, April 2008.
483 # Create a temporary directory based on
484 # $ENV{ 'BP_TMP' } and sessionid.
486 # this thing is a really bad solution and needs to be removed.
490 my ( $user, $sid, $pid, $path );
492 Maasha::Common::error( qq(no BP_TMP set in %ENV) ) if not -d $ENV{ 'BP_TMP' };
494 $user = Maasha::Common::get_user();
495 $sid = Maasha::Common::get_sessionid();
496 $pid = Maasha::Common::get_processid();
498 $path = "$ENV{ 'BP_TMP' }/" . join( "_", $user, $sid, $pid, "bp_tmp" );
500 Maasha::Filesys::dir_create( $path );
508 # Martin A. Hansen, February 2007
510 # returns the script name
512 return ( split "/", $0 )[ -1 ];
518 # Martin A. Hansen, February 2007
520 # Given a full path to a file returns the basename,
521 # which is the part of the name before the last '.'.
523 my ( $path, # full path to filename
528 $basename = ( split "/", $path )[ -1 ];
530 $basename =~ s/(.+)\.?.*/$1/;
538 # Martin A. Hansen, July 2008.
540 # Given a filehandle to a file gets the
541 # next line which is split into a list of
542 # fields that is returned.
544 my ( $fh, # filehandle
545 $delimiter, # field seperator - OPTIONAL
550 my ( $line, @fields );
554 return if not defined $line;
560 @fields = split "$delimiter", $line;
562 return wantarray ? @fields : \@fields;
568 # Martin A. Hansen, April 2007.
570 # Run an execute with optional arguments.
572 my ( $exe, # executable to run
573 $args, # argument string
579 my ( $command_line, $result );
581 $command_line = Maasha::Config::get_exe( $exe );
582 $command_line .= " " . $args if $args;
583 $command_line = "nice -n19 " . $command_line if $nice;
585 system( $command_line ) == 0 or Maasha::Common::error( qq(Could not execute "$command_line": $?) );
591 # Martin A. Hansen, April 2008.
593 # Run an execute with optional arguments returning the output
596 my ( $exe, # executable to run
597 $args, # argument string
603 my ( $command_line, @result );
605 $command_line = Maasha::Config::get_exe( $exe );
606 $command_line .= " " . $args if $args;
607 $command_line = "nice -n19 " . $command_line if $nice;
609 @result = `$command_line`;
613 return wantarray ? @result : \@result;
619 # Martin A. Hansen, February 2006.
621 # returns timestamp for use in log file.
622 # format: YYYY-MM-DD HH:MM:SS
626 my ( $year, $mon, $day, $time );
628 ( undef, undef, undef, $day, $mon, $year, undef, undef ) = gmtime( time );
630 $mon += 1; # first month is 0, so we correct accordingly
633 $day = sprintf "%02d", $day;
634 $mon = sprintf "%02d", $mon;
638 $time =~ s/.*(\d{2}:\d{2}:\d{2}).*/$1/;
640 return "$year-$mon-$day $time";
646 # Martin A. Hansen, July 2008.
648 # Given a process ID check if it is running
649 # on the system. Return 1 if the process is
652 my ( $pid, # process ID to check.
659 @ps_table = run_and_return( "ps", " a" );
661 if ( grep /^\s*$pid\s+/, @ps_table ) {
671 # Martin A. Hansen, May 2005
673 # Takes a given line and wraps it to a given width,
674 # without breaking any words.
676 my ( $line, # line to wrap
680 # Returns a list of lines.
682 my ( @lines, $substr, $wrap_pos, $pos, $new_line );
686 while ( $pos < length $line )
688 $substr = substr $line, $pos, $width;
690 if ( length $substr == $width )
692 $substr = reverse $substr;
693 $wrap_pos = index $substr, " ";
695 $new_line = substr $line, $pos, $width - $wrap_pos;
698 $pos += $width - $wrap_pos;
707 push @lines, $new_line;
710 return wantarray ? @lines : \@lines;
714 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<