/[cvs]/nfo/perl/libs/shortcuts.pm
ViewVC logotype

Diff of /nfo/perl/libs/shortcuts.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.6 by joko, Fri Mar 28 06:58:06 2003 UTC revision 1.18 by joko, Fri Dec 5 04:58:04 2003 UTC
# Line 2  Line 2 
2  ##  $Id$  ##  $Id$
3  ## ---------------------------------------------------------------------------  ## ---------------------------------------------------------------------------
4  ##  $Log$  ##  $Log$
5    ##  Revision 1.18  2003/12/05 04:58:04  joko
6    ##  + minor update: doesn't require IPC::Session anymore
7    ##
8    ##  Revision 1.17  2003/07/02 11:17:32  jonen
9    ##  minor changes
10    ##
11    ##  Revision 1.16  2003/06/25 22:49:56  joko
12    ##  RUNNING_IN_HELL mode for detach option
13    ##
14    ##  Revision 1.15  2003/06/24 20:21:12  jonen
15    ##  + changed linux part of run_cmd to use Proc::Background instead of IPC::...
16    ##
17    ##  Revision 1.14  2003/06/24 20:13:18  joko
18    ##  + sub findpatch
19    ##  + now using findpatch and Proc::Background for win32/perl
20    ##
21    ##  Revision 1.13  2003/06/23 20:58:31  joko
22    ##  restructured, hopefully makes Linux and Windows (and *BSD) more compatible...  what about IPC::Cmd???
23    ##
24    ##  Revision 1.12  2003/06/23 19:43:19  joko
25    ##  minor cleanup
26    ##  now using IPC::Session::NoShell
27    ##
28    ##  Revision 1.11  2003/06/23 17:41:50  jonen
29    ##  + NEW - used IPC::Session instead of IPC::Run to get better results at linux
30    ##
31    ##  Revision 1.10  2003/06/23 15:59:16  joko
32    ##  major/minor fixes?
33    ##
34    ##  Revision 1.9  2003/05/13 05:36:24  joko
35    ##  heavy modifications to run_cmd
36    ##  + sub get_executable
37    ##  + sub get_executable_wrapper
38    ##
39    ##  Revision 1.8  2003/04/04 17:31:59  joko
40    ##  + sub make_guid
41    ##
42    ##  Revision 1.7  2003/03/29 07:24:10  joko
43    ##  enhanced 'run_cmd': now tries to execute program with appropriate application (e.g. 'cmd.exe' or 'perl')
44    ##
45  ##  Revision 1.6  2003/03/28 06:58:06  joko  ##  Revision 1.6  2003/03/28 06:58:06  joko
46  ##  new: 'run_cmd' now asynchronous! (via IPC::Run...)  ##  new: 'run_cmd' now asynchronous! (via IPC::Run...)
47  ##  ##
# Line 36  our @EXPORT_OK = qw( Line 76  our @EXPORT_OK = qw(
76    run_cmd run_cmds    run_cmd run_cmds
77    get_chomped    get_chomped
78    bool2status    bool2status
79      make_guid
80  );  );
81    
82    
 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -   main  
   
83  use Data::Dumper;  use Data::Dumper;
84  use POSIX qw( strftime );  use POSIX qw( strftime );
85  #use IPC::Run qw( run timeout );  #use IPC::Run qw( run timeout );
86  use IPC::Run qw( start pump finish timeout ) ;  use IPC::Run qw( start pump finish timeout run timer ) ;
87    use Carp;
88    
89    # NEW - 2003-06-23 for Linux (what about *BSD?)
90    #use IPC::Session;
91    
92    use File::Spec;
93    use Proc::Background;
94    
95    
96  # $now_string = strftime "%a %b %e %H:%M:%S %Y", localtime;  # $now_string = strftime "%a %b %e %H:%M:%S %Y", localtime;
97  # see "perldoc -f localtime"  # see "perldoc -f localtime"
   
98  sub now {  sub now {
99    my $options = shift;    my $options = shift;
100    my $pattern = "%Y-%m-%d %H:%M:%S";    my $pattern = "%Y-%m-%d %H:%M:%S";
# Line 61  sub today { Line 107  sub today {
107    return strftime("%Y-%m-%d", localtime);    return strftime("%Y-%m-%d", localtime);
108  }  }
109    
110    sub RUNNING_IN_HELL () { $^O eq 'MSWin32' }
111    
112    
113    sub get_executable {
114      my $cmd = shift;
115      # FIXME: detect type of program and run with proper application/interpreter
116      # using IPC::Run we have to dispatch this on our own! *no* os-interaction or interpolation here!?
117      # => better use absolute path-names only?!
118      my $application = '';
119      if ($cmd =~ m/\w+\.pl\s*.*/) {
120          $application = get_interpreter_wrapper($cmd, 'perl');
121          #$cmd = "$application $cmd" if $application;
122          $application .= ' ';
123        
124      } else {
125        $application = './';
126      }
127      return $application;
128    }
129    
130    sub get_interpreter_wrapper {
131      my $cmd = shift;
132      my $language = shift;
133      $language ||= '';
134    
135      my $wrapper = '';
136    
137      if ($language eq 'perl') {
138      
139        if (RUNNING_IN_HELL()) {
140          # Required to adapt to IPC::Run on win32.
141          #$wrapper = 'cmd.exe /C perl';
142          #$wrapper = 'start perl';
143          $wrapper = 'perl';
144          #$wrapper = 'cmd.exe /C';
145        } else {
146          # NEW 2003-06-23 - needed if used with IPC::Session (at Linux)
147          #  whats about Win32?
148          $wrapper = 'perl';
149        }
150        
151      } else {
152        die("No wrapper for language '$language'.");
153      }
154      
155      return $wrapper;
156    }
157    
158    
159  sub run_cmd {  sub run_cmd {
160    my $cmd = shift;    my $cmd = shift;
161    my $caption = shift;    my $caption = shift;
162    my $options = shift;    my $options = shift;
163    #$cmd = 'perl ' . $cmd;    
164      #print STDOUT "run_cmd - options: ", Dumper($options), "\n";
165        
166    # report - header    # report - header
167    my $sep = "-" x 60;    my $sep = "-" x 60;
168    print $sep, "\n";    print STDOUT $sep, "\n";
169    #print "  ", $cmd, "\n";    print STDOUT "  ", $cmd;
170    #print "  ", "  $caption", "\n" if $caption;    print STDOUT " - ", $caption if $caption;
171    print "  ", $cmd;    print STDOUT "\n", $sep, "\n";
   print " - ", $caption if $caption;  
   print "\n";  
   print $sep, "\n";  
172        
173    # strip name of executable from full command string    # strip name of executable from full command string
174    $cmd =~ m/(.+?)\s/;    $cmd =~ m/^(.+?)\s(.*)$/;
175    my $executable = $1;    my $executable = $1;
176      my $executable_args = $2;
177        
178    =pod
179    # for unix: check if executable is in local directory, if so - prefix with './'    # for unix: check if executable is in local directory, if so - prefix with './'
180    if (!RUNNING_IN_HELL()) {    if (!RUNNING_IN_HELL()) {
181      #if ($cmd !~ m/\//) {      #if ($cmd !~ m/\//) {
182      if (-e $executable) {      if (-e $executable) {
       $cmd = "./$cmd";  
183      }      }
184    }    }
185      =cut
186    
187      # new of 2003-05-07: basedir option to be prepended to command string
188      my $basedir = $options->{BASEDIR};
189      my $use_path = $options->{USE_PATH};
190    
191      # for all systems: check existance of files - use basedir if given, try current directory otherwise
192      if ($basedir) {
193        -e "$basedir/$executable" or die("$basedir/$executable does not exist.");
194        $basedir .= '/';
195        $cmd = "$basedir$cmd";
196      } elsif ($use_path) {
197        #$basedir = "";
198        $basedir = findpath($executable);
199        #print "basedir: $basedir", "\n";
200        my $abspath = File::Spec->catfile($basedir, $executable);
201        #print STDOUT "PATH: ", $abspath, "\n";
202        -e $abspath or die("$abspath does not exist.");
203        $cmd = $abspath . ' ' . $executable_args;
204      } else {
205        -e $executable or die("$executable does not exist.");
206        #$basedir = ".";
207        #$basedir .= './';
208        $basedir = "";
209        $cmd = "$basedir$cmd";
210      }
211    
212    # V1 - backticks or qq{}    # V1 - backticks or qq{}
213    #`$cmd`;    #`$cmd`;
214    #qq{$cmd};    #qq{$cmd};
# Line 96  sub run_cmd { Line 216  sub run_cmd {
216    # V2 - via 'system'    # V2 - via 'system'
217    #system($cmd);    #system($cmd);
218    
219    # V3 - using IPC::Run (optional)    #if (not $use_path) {
220        my $application = get_executable($cmd);
221        $cmd = "$application$cmd" if $application;
222      #}
223    
224      my @cmd = split(' ', $cmd);
225    
226      # V3 - using IPC (optional)
227    if ($options->{async}) {    if ($options->{async}) {
228      # FIXME: detect type of program and run with proper application/interpreter  
     # using IPC::Run we have to dispatch this on our own! *no* os-interaction or interpolation here!  
     # => better use absolute path-names only?!  
     $cmd = "perl $cmd";  
     print "IPC::Run: $cmd", "\n";  
229      #run \@cmd, \$in, \$out, \$err, timeout( 10 ) or die "cat: $?";      #run \@cmd, \$in, \$out, \$err, timeout( 10 ) or die "cat: $?";
230    
231        print STDOUT "run_cmd[async]: Proc::Background: $cmd", "\n";
232            
233      my @cmd = split(' ', $cmd);      # V3.1 - using IPC::Run
234            #
235      my $in; my $out; my $err;      # tests:
     start \@cmd, timeout(0) or die("IPC::Run could not start '$cmd'.");  
236            
237      #$IPC::Run::Timer::timeout = 2000;      if (RUNNING_IN_HELL()) {
     #start $cmd or die("IPC::Run could not start '$cmd'.");  
238            
239          #my $in; my $out; my $err;
240          
241          #print STDOUT "findpath: ", findpath('rap.pl'), "\n";
242          
243          # no success!
244          #start \@cmd, timeout(0) or croak("run_cmd: IPC::Run could not start '$cmd'.");
245          #
246          # success on Win32, but seems broken at 'timeout' on linux:
247          #run(\@cmd, timeout(3)) or croak("run_cmd: IPC::Run could not start '$cmd'.");
248          #start(\@cmd, timer(2)) or croak("run_cmd: IPC::Run could not start '$cmd'.");
249          #start(\@cmd, \undef) or croak("run_cmd: IPC::Run could not start '$cmd'.");
250          #start \@cmd or croak("run_cmd: IPC::Run could not start '$cmd'.");
251          #start(\@cmd, timeout(1)) or croak("run_cmd: IPC::Run could not start '$cmd'.");      
252              
253          # other tests ;)
254          #$IPC::Run::Timer::timeout = 2000;
255          #start $cmd or die("IPC::Run could not start '$cmd'.");
256          
257          #my $in; my $out; my $t;
258          #my $harness = start( \@cmd, \$in, \$out, $t = timer( 5 ) ) ;
259          #my $harness = start( \@cmd ) ;
260          #$harness->pump_nb();
261          
262          #my $postfix = '2>&1 |';
263          #open PIPE, "$cmd $postfix" or die("run_cmd: could not run in background via open!");
264          
265          my $proc1 = Proc::Background->new(@cmd);
266          print "pid: ", $proc1->pid(), "\n";
267    
268          
269        } else {
270    
271          #print STDOUT "run_cmd: IPC::Session: $cmd", "\n";
272    
273          # V3.2 - using IPC::Session
274          #  success on Linux AND Win32 ??
275          #
276          # set timeout:
277          #  (don't really know why we needs some secconds
278          #   to wait for init of process !?!)
279          #my $session_timeout = 15;
280          # set session name (default: cmd as string):
281          #my $session_command = $cmd;
282          #my $session_shell = "/bin/sh";
283          # create session (beware of using '->new' here!?):
284          #my $session = new IPC::Session($session_shell, $session_timeout);
285          
286          # send 'cmd' to session - not required since complete command is sent via constructor above
287          #$session->send($cmd);
288    
289          #my $output = $session->stdout();
290          #print "WS::Admin started.\n" if $output = ' ';
291    
292          # tests
293          #$session->send("echo hello");
294          #chomp(my $hello = $session->stdout());      
295          #print "ok 3\n" if $hello eq "hello";
296          
297          # optional switch case:
298          #for ($session->stdout()) {
299          #  /_bootDataBases/ && do { print "WS::Admin started.\n" };
300          #}
301          # optional get error:
302          #my $err = session->stderr();
303          #print "ERR: " . Dumper($err) . "\n";
304    
305          #open( *OUT, ">out.txt" ) ;
306          #open( *ERR, ">err.txt" ) ;
307          #run(\@cmd, \undef,  \*OUT, \*ERR  ) or croak("run_cmd: IPC::Run could not start '$cmd'.");
308          #my ($out, $err);
309          #my $h = start(\@cmd, \undef,  \*OUT, \*ERR  ) or croak("run_cmd: IPC::Run could not start '$cmd'.");
310          #finish $h if $err =~ /error/;
311          
312          # get child pid
313          #my $kid;
314          #do { $kid=wait(); } until $kid > 0;
315          #print "Child PID: " . $kid . "n";
316    
317          #finish $h;
318    
319          
320          # test using Proc::Background - success !!
321          my $proc = Proc::Background->new($cmd);
322          my $kid = $proc->pid();
323          print STDOUT "run_cmd: Proc::Background: $cmd, child PID $kid", "\n";
324          $proc->wait();
325          $proc->die();
326    
327        }
328    
329    
330      } elsif ($options->{detach}) {
331    
332        if (RUNNING_IN_HELL()) {
333          print STDOUT "run_cmd[detach]: Proc::Background: $cmd", "\n";
334          my $proc1 = Proc::Background->new(@cmd);
335          print "pid: ", $proc1->pid(), "\n";
336        } else {
337          print STDOUT "run_cmd[detach]: system('$cmd' &).", "\n";
338          system($cmd . ' &');    
339        }
340    
341    } else {    } else {
342        print STDOUT "run_cmd: system('$cmd').", "\n";
343        #print $ENV{PERL5LIB}, "\n";
344      system($cmd);      system($cmd);
345    }    }
346        
347    print "ready.", "\n";    print STDOUT "run_cmd: ready.", "\n";
348        
349  }  }
350    
351  sub run_cmds {  sub run_cmds {
352      my $options = {};
353      if (ref $_[$#_] eq 'HASH') {
354        #print "YAI", "\n";
355        $options = pop @_;
356      }
357    foreach (@_) {    foreach (@_) {
358      run_cmd($_);      run_cmd($_, '', $options);
359    }    }
360  }  }
361    
# Line 138  sub bool2status { Line 370  sub bool2status {
370    return ($bool ? 'ok' : 'failed');    return ($bool ? 'ok' : 'failed');
371  }  }
372    
373  sub RUNNING_IN_HELL () { $^O eq 'MSWin32' }  # create global unique identifers using Data::UUID
374    # if updating this code, please also modify Tangram::Storage::make_guid
375    sub make_guid
376      {
377        my $self = shift;
378    
379        my $guid;
380    
381        # try to use Data::UUID first ...
382        eval("use Data::UUID;");
383        if (!$@) {
384          my $ug = Data::UUID->new();
385          $guid = $ug->create_str();
386          
387        # ... if this fails, try to fallback to Data::UUID::PurePerl instead ...
388        } else {
389          eval("use Data::UUID::PurePerl;");
390          if (!$@) {
391            $guid = Data::UUID::PurePerl::generate_id();
392          } else {
393            croak "couldn't create globally unique identifier";
394          }
395        }
396        
397        return $guid;
398      }
399    
400    # [modified] from: http://www.mit.edu/afs/athena/contrib/watchmaker/src/pt/Configure
401    sub findpath {
402        #local($path);
403        #local($arg) = shift;
404        my $arg = shift;
405        my $path;
406        #for my $dir (split(/:/,$ENV{'PATH'})) {
407        for my $dir (File::Spec->path()) {
408            #if (-x "$dir/$arg" && -f _) {
409            #print STDOUT "scanning: ", "$dir/$arg", "\n";
410            if (-e "$dir/$arg") {
411                #$path = "$dir/$arg";
412                #$path = "$dir/";
413                $path = $dir;
414                last;
415            }
416        }
417        $path;
418    }
419    
420  1;  1;
421    __END__

Legend:
Removed from v.1.6  
changed lines
  Added in v.1.18

MailToCvsAdmin">MailToCvsAdmin
ViewVC Help
Powered by ViewVC 1.1.26 RSS 2.0 feed