lib/Treex/Core/Run.pm

filter: Statementstmt 36.3% 185 / 509 Branchbran 24.4% 45 / 184 Conditioncond 19.3% 11 / 57 MC/DCmcdc 2.8% 1 / 35 Subroutinesub 60.4% 26 / 43 Podpod 33.3% 1 / 3 totaltotal 32.3% 269 / 831 CC 122 SCAR 44.2
CC
122
Cov
32%
_print_output_files
342.0
_run_job_scripts
182.0
_wait_for_jobs
110.0
CRAP 82.9
« lib/Treex/Core/Resource.pm ↑ Summary lib/Treex/Core/DocumentReader/Base.pm »
1 package Treex::Core::Run;
2 {
3 28 $Treex::Core::Run::VERSION = '0.08633_1';
4 }
5 28 ▶use 5.008;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 28 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 28 ▶use Treex::Core::Common;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 28 ▶use Treex::Core;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 28 ▶use MooseX::SemiAffordanceAccessor 0.09;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 28 with 'MooseX::Getopt';
11  
12 28 ▶use Cwd;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 28 ▶use File::Path;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 28 ▶use File::Temp qw(tempdir);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 28 ▶use File::Which;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 28 ▶use List::MoreUtils qw(first_index);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 28 ▶use IO::Interactive;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 28 ▶use Time::HiRes;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 28 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 28 ▶use base 'Exporter';
Subroutine BEGIN: called CC=1 SCAR=0.0
21 28 our @EXPORT_OK = q(treex);
22  
23 28 has 'save' => (
24 traits => ['Getopt'],
25 cmd_aliases => 's',
26 is => 'rw',
27 isa => 'Bool',
28 default => 0,
29 documentation => 'save all documents',
30 );
31  
32 has 'quiet' => (
33 traits => ['Getopt'],
34 cmd_aliases => 'q',
35 is => 'rw',
36 isa => 'Bool',
37 default => 0,
38 25 ▶ trigger => sub { Treex::Core::Log::log_set_error_level('FATAL'); },
Subroutine __ANON__: called CC=1 SCAR=0.0
39 28 documentation => q{Warning, info and debug messages are suppressed. Only fatal errors are reported.},
40 );
41  
42 28 has 'cleanup' => (
43 traits => ['Getopt'],
44 is => 'rw', isa => 'Bool', default => 0,
45 documentation => q{Delete all temporary files.},
46 );
47  
48 has 'error_level' => (
49 traits => ['Getopt'],
50 cmd_aliases => 'e',
51 is => 'rw', isa => 'ErrorLevel', default => 'INFO',
52 0 ▶ trigger => sub { Treex::Core::Log::log_set_error_level( $_[1] ); },
Subroutine __ANON__: not called CC=1 SCAR=6.9
53 28 documentation => q{Possible values: ALL, DEBUG, INFO, WARN, FATAL},
54 );
55  
56 28 has 'forward_error_level' => (
57 traits => ['Getopt'],
58 cmd_aliases => 'E',
59 is => 'rw', isa => 'ErrorLevel', default => 'WARN',
60 documentation => q{messages with this level or higher will be forwarded from the distributed jobs to the main STDERR},
61 );
62  
63 28 has 'lang' => (
64 traits => ['Getopt'],
65 cmd_aliases => [ 'language', 'L' ],
66 is => 'rw', isa => 'Treex::Type::LangCode',
67 documentation => q{shortcut for adding "Util::SetGlobal language=xy" at the beginning of the scenario},
68 );
69  
70 28 has 'selector' => (
71 traits => ['Getopt'],
72 cmd_aliases => 'S',
73 is => 'rw', isa => 'Treex::Type::Selector',
74 documentation => q{shortcut for adding "Util::SetGlobal selector=xy" at the beginning of the scenario},
75 );
76  
77 # treex -h should not print "Unknown option: h" before the usage.
78 #has 'help' => (
79 # traits => ['Getopt'],
80 # cmd_aliases => 'h',
81 # is => 'ro', isa => 'Bool', default => 0,
82 # documentation => q{Print usage info},
83 #);
84  
85 28 has 'filenames' => (
86 traits => ['NoGetopt'],
87 is => 'rw',
88 isa => 'ArrayRef[Str]',
89 documentation => 'treex file names',
90 );
91  
92 28 has 'glob' => (
93 traits => ['Getopt'],
94 cmd_aliases => 'g',
95 is => 'rw',
96 isa => 'Str',
97 documentation => q{Input file mask whose expansion is to Perl, e.g. --glob '*.treex'},
98 );
99  
100 28 has 'scenario' => (
101 traits => ['NoGetopt'],
102 is => 'rw',
103 isa => 'Treex::Core::Scenario',
104 predicate => '_has_scenario',
105 documentation => 'scenario object',
106 );
107  
108 28 has 'parallel' => (
109 traits => ['Getopt'],
110 cmd_aliases => 'p',
111 is => 'rw',
112 isa => 'Bool',
113 default => 0,
114 documentation => 'Parallelize the task on SGE cluster (using qsub).',
115 );
116  
117 28 has 'jobs' => (
118 traits => ['Getopt'],
119 cmd_aliases => 'j',
120 is => 'ro',
121 isa => 'Int',
122 default => 10,
123 documentation => 'Number of jobs for parallelization, default 10. Requires -p.',
124 );
125  
126 28 has 'jobindex' => (
127 traits => ['Getopt'],
128 is => 'ro',
129 isa => 'Int',
130 documentation => 'Not to be used manually. If number of jobs is set to J and modulo set to M, only I-th files fulfilling I mod J == M are processed.',
131 );
132  
133 28 has 'outdir' => (
134 traits => ['Getopt'],
135 is => 'ro',
136 isa => 'Str',
137 documentation => 'Not to be used manually. Dictory for collecting standard and error outputs in parallelized processing.',
138 );
139  
140 28 has 'local' => (
141 traits => ['Getopt'],
142 is => 'ro',
143 isa => 'Bool',
144 documentation => 'Run jobs locally (might help with multi-core machines). Requires -p.',
145 );
146  
147 28 has 'priority' => (
148 traits => ['Getopt'],
149 is => 'ro',
150 isa => 'Int',
151 default => -100,
152 documentation => 'Priority for qsub, an integer in the range -1023 to 0 (or 1024 for admins), default=-100. Requires -p.',
153 );
154  
155 28 has 'mem' => (
156 traits => ['Getopt'],
157 cmd_aliases => [ 'm', 'memory' ],
158 is => 'ro',
159 isa => 'Str',
160 default => '2G',
161 documentation => 'How much memory should be allocated for cluster jobs, default=2G. Requires -p. '
162 . 'Translates to "qsub -hard -l mem_free=$mem -l act_mem_free=$mem -l h_vmem=$mem".',
163 );
164  
165 28 has 'qsub' => (
166 traits => ['Getopt'],
167 is => 'ro',
168 isa => 'Str',
169 default => '',
170 documentation => 'Additional parameters passed to qsub. Requires -p. See --priority and --mem.',
171 );
172  
173 28 has 'watch' => (
174 traits => ['Getopt'],
175 is => 'ro',
176 isa => 'Str',
177 documentation => 're-run when the given file is changed TODO better doc',
178 );
179  
180 28 has 'workdir' => (
181 is => 'rw',
182 traits => ['Getopt'],
183 isa => 'Str',
184 documentation => 'working directory for temporary files in parallelized processing ' .
185 '(if not specified, directories such as 001-cluster-run, 002-cluster-run etc. are created)',
186 );
187  
188 has 'sge_job_numbers' => (
189 is => 'rw',
190 traits => ['NoGetopt'],
191 documentation => 'list of numbers of jobs executed on sge',
192 27 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
193 28 );
194  
195 28 has 'dump_scenario' => (
196 traits => ['Getopt'],
197 cmd_aliases => 'd',
198 is => 'rw',
199 isa => 'Bool',
200 default => 0,
201 documentation => 'Just dump (print to STDOUT) the given scenario and exit.',
202 );
203  
204 28 has 'dump_required_files' => (
205 traits => ['Getopt'],
206 is => 'rw',
207 isa => 'Bool',
208 default => 0,
209 documentation => 'Just dump (print to STDOUT) files required by the given scenario and exit.',
210 );
211  
212 28 has 'survive' => (
213 traits => ['Getopt'],
214 is => 'rw',
215 isa => 'Bool',
216 default => 0,
217 documentation => 'Continue collecting jobs\' outputs even if some of them crashed (risky, use with care!).',
218 );
219  
220 has version => (
221 traits => ['Getopt'],
222 is => 'ro',
223 isa => 'Bool',
224 default => 0,
225 cmd_aliases => 'v',
226 documentation => q(Print treex and perl version),
227 trigger => sub {
228 2 ▶ print get_version();
Subroutine __ANON__: called CC=1 SCAR=0.0
229 2 exit();
230 },
231 28 );
232  
233 sub _usage_format {
234 27 ▶ return "usage: %c %o scenario [-- treex_files]\nscenario is a sequence of blocks or *.scen files\noptions:";
Subroutine _usage_format: called CC=1 SCAR=0.0
235 }
236  
237 #gets info about version of treex and perl
238 sub get_version {
239 4 ▶ my $perl_v = $^V;
Subroutine get_version: called CC=4 SCAR=16.1
Pod undocumented
240 4 my $perl_x = $^X;
241 4 ▶ my $treex_v = $Treex::Core::Run::VERSION || 'DEV';
Condition50%1/2
$Treex::Core::Run::VERSION || 'DEV'
l!l
40
MC/DC0%0/1
$Treex::Core::Run::VERSION || 'DEV'
$Treex::Core::Run::VERSION
Truth table50%1/2
A
A= $Treex::Core::Run::VERSION
Aresult
11
00
242 4 my $treex_x = which('treex');
243  
244 # File::Which::which sometimes fails to found treex.
245 4 ▶ if ( !defined $treex_x ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $treex_x) 0 4 4
246 0 chomp( $treex_x = `which treex 2> /dev/null` );
247 0 ▶ $treex_x ||= '<treex not found in $PATH>';
Condition0%0/2
$treex_x ||= "<treex not found in \$PATH>"
l!l
00
MC/DC0%0/1
$treex_x ||= "<treex not found in \$PATH>"
$treex_x
Truth table0%0/2
A
A= $treex_x
Aresult
11
00
248 }
249 4 my $version_string = <<"VERSIONS";
250 Treex version: $treex_v from $treex_x
251 Perl version: $perl_v from $perl_x
252 VERSIONS
253 4 return $version_string;
254 }
255  
256 sub BUILD {
257  
258 # more complicated tests on consistency of options will be place here
259 25 ▶ my ($self) = @_;
Subroutine BUILD: called CC=8 SCAR=23.6
Pod undocumented
260 25 ▶ if ( $self->jobindex ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->jobindex) 0 25 25
261 0 _redirect_output( $self->outdir, 0, $self->jobindex );
262 }
263  
264 25 my @file_sources;
265 25 ▶ if ( $self->filenames ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->filenames) 8 17 25
266 8 push @file_sources, "files after --";
267 }
268 25 ▶ if ( $self->glob ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->glob) 2 23 25
269 2 push @file_sources, "glob option";
270 }
271 25 ▶ if ( @file_sources > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@file_sources > 1) 0 25 25
272 0 log_fatal "At most one way to specify input files can be used. You combined "
273 . ( join " and ", @file_sources ) . ".";
274 }
275  
276 # 'require' can't be changed to 'imply', since the number of jobs has a default value
277 25 ▶ if ( ( $self->qsub || $self->jobindex ) && !$self->parallel ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->qsub || $self->jobindex and not $self->parallel) 0 25 25
Condition33%2/6
$self->qsub || $self->jobindex and not $self->parallel
!ll&&!rl&&r
2500
$self->qsub or $self->jobindex
l!l&&r!l&&!r
0025
MC/DC0%0/3
$self->qsub || $self->jobindex and not $self->parallel
$self->qsub $self->jobindex not $self->parallel
Truth table20%1/5
A or B and not(C)
A= $self->qsubB= $self->jobindexC= not $self->parallel
ABCresult
00X0
1X00
0100
1X11
0111
278 0 log_fatal "Options --qsub and --jobindex require --parallel";
279 }
280 25 return;
281 }
282  
283 sub _execute {
284 25 ▶ my ($self) = @_;
Subroutine _execute: called CC=16 SCAR=44.9
285 25 ▶ if ( $self->dump_scenario || $self->dump_required_files ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->dump_scenario or $self->dump_required_files) 0 25 25
Condition33%1/3
$self->dump_scenario or $self->dump_required_files
l!l&&r!l&&!r
0025
MC/DC0%0/2
$self->dump_scenario or $self->dump_required_files
$self->dump_scenario $self->dump_required_files
Truth table33%1/3
A or B
A= $self->dump_scenarioB= $self->dump_required_files
ABresult
1X1
011
000
286  
287 # TODO: execute_locally does the same work as the following line in a more safe ways
288 # (If someone wants to run treex -d My::Block my_scen.scen)
289 0 my $scen_str = join ' ', @{ $self->extra_argv };
290 0 $self->set_scenario( Treex::Core::Scenario->new( scenario_string => $scen_str, runner => $self ) );
291  
292 # TODO: Do it properly - perhaps, add a Scenario option to not load all the blocks.
293 # We cannot create the real scenario instance without loading all the blocks
294 # However, since r6307 some Scenario's functions were changed to methods, so we must create a dummy instance.
295  
296 #my @block_items = Treex::Core::Scenario::parse_scenario_string($scen_str);
297 #my @block_items = $dummy_scenario->parse_scenario_string($scen_str);
298  
299 0 ▶ if ( $self->dump_scenario ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->dump_scenario) 0 0 0
300 0 print "# Full Scenario generated by 'treex --dump_scenario' on " . localtime() . "\n";
301 0 print $self->scenario->construct_scenario_string( multiline => 1 ), "\n";
302 }
303  
304 0 ▶ if ( $self->dump_required_files ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->dump_required_files) 0 0 0
305 0 print "# Required files generated by 'treex --dump_required_files' on " . localtime() . "\n";
306 0 print join "\n", $self->scenario->get_required_files(), "\n";
307 }
308 0 exit;
309 }
310  
311 25 ▶ if ( $self->dump_required_files ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->dump_required_files) 0 25 25
312  
313 0 my $scen_str = join ' ', @{ $self->extra_argv };
314 0 $self->set_scenario( Treex::Core::Scenario->new( scenario_string => $scen_str, runner => $self ) );
315  
316 0 print "# Required files generated by 'treex --dump_required_files' on " . localtime() . "\n";
317 0 print join "\n", $self->scenario->get_required_files(), "\n";
318 0 exit;
319 }
320  
321 25 my $done = 0;
322 25 my $time;
323 25 my $watch = $self->watch;
324  
325 25 ▶ if ( defined $watch ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $watch) 0 25 25
326 0 ▶ log_fatal "Watch file '$watch' does not exists" if !-f $watch;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $watch 0 0 0
327 0 $time = ( stat $watch )[9];
328 }
329  
330 25 ▶ while ( !$done ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($done) 25 25 50
331 25 ▶ if ( $self->parallel && !defined $self->jobindex ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->parallel and not defined $self->jobindex) { } 0 25 25
Condition33%1/3
$self->parallel and not defined $self->jobindex
!ll&&!rl&&r
2500
MC/DC0%0/2
$self->parallel and not defined $self->jobindex
$self->parallel not defined $self->jobindex
Truth table33%1/3
A and not(B)
A= $self->parallelB= not defined $self->jobindex
ABresult
0X0
100
111
332 0 log_info "Parallelized execution. This process is the head coordinating "
333 . $self->jobs . " server processes.";
334 0 $self->_execute_on_cluster();
335 }
336  
337 # non-parallelized execution, or one of distributed processes
338 else {
339 25 ▶ if ( $self->parallel ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->parallel) { } 0 25 25
340 0 log_info "Parallelized execution. This process is one out of "
341 . $self->jobs . " server processes, jobindex==" . $self->jobindex;
342 }
343 else {
344 25 log_info "Local (single-process) execution.";
345 }
346 25 $self->_execute_locally();
347 }
348  
349 25 $done = 1;
350 25 my $info_written = 0;
351 WATCH_CHANGE:
352 25 ▶ while ( defined $watch && -f $watch ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $watch and -f $watch) 0 25 25
Condition33%1/3
defined $watch and -f $watch
!ll&&!rl&&r
2500
MC/DC0%0/2
defined $watch and -f $watch
defined $watch -f $watch
Truth table33%1/3
A and B
A= defined $watchB= -f $watch
ABresult
0X0
100
111
353 0 my $new_time = ( stat $watch )[9];
354 0 ▶ if ( $new_time > $time ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($new_time > $time) 0 0 0
355 0 $time = $new_time;
356 0 $done = 0;
357 0 last WATCH_CHANGE;
358 }
359 0 ▶ if ( !$info_written ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($info_written) 0 0 0
360 0 log_info "Watching '$watch' file. Touch it to re-run, delete to quit.";
361 0 $info_written = 1;
362 }
363 0 sleep 1;
364 }
365 }
366 25 return;
367 }
368  
369 28 my %READER_FOR = (
370 'treex' => 'Treex',
371 'treex.gz' => 'Treex',
372 'txt' => 'Text',
373 'txt.gz' => 'Text',
374 'streex' => 'Treex',
375 'mrg' => 'PennMrg',
376 'mrg.gz' => 'PennMrg',
377 'tag' => 'CdtTag',
378  
379 # TODO:
380 # conll => 'Conll',
381 # plsgz => 'Plsgz',
382 # tmt
383 );
384  
385 sub _get_reader_name_for {
386 23 ▶ my $self = shift;
Subroutine _get_reader_name_for: called CC=6 SCAR=17.9
387 23 my @names = @_;
388 23 my $base_re = join( '|', keys %READER_FOR );
389 23 my $re = qr{\.($base_re)$};
390 23 my @extensions;
391 my $first;
392  
393 23 foreach my $name (@names) {
394 34 ▶ if ( $name =~ /$re/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name =~ /$re/) { } 30 4 34
395 30 my $current = $1;
396 30 $current =~ s/\.gz$//;
397 30 ▶ if ( !defined $first ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $first) 19 11 30
398 19 $first = $current;
399 }
400 30 ▶ if ( $current ne $first ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($current ne $first) 1 29 30
401 1 log_fatal 'All files (' . join( ',', @names ) . ') must have the same extension' . "\n" .
402 " current = $current\n" .
403 " first = $first\n" .
404 " curname = $name";
405 }
406 29 push @extensions, $current;
407 }
408 else {
409 4 log_fatal 'Files (' . join( ',', @names ) . ') must have extensions';
410 }
411 }
412 18 my $r = $READER_FOR{$first};
413 18 ▶ log_fatal "There is no DocumentReader implemented for extension '$first'" if !$r;
Branch: 1 branch
BranchTrueFalseTotal
unless $r 1 17 18
414 17 return "Read::$r";
415 }
416  
417 sub _execute_locally {
418 25 ▶ my ($self) = @_;
Subroutine _execute_locally: called CC=16 SCAR=31.9
419  
420 # Parameters can contain whitespaces that should be preserved
421 25 my @arguments;
422 25 foreach my $arg ( @{ $self->extra_argv } ) {
423 66 ▶ if ( $arg =~ /(\S+)=(.*\s.*)$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($arg =~ /(\S+)=(.*\s.*)$/) { } 16 50 66
424 16 my ( $name, $value ) = ( $1, $2 );
425 16 $value =~ s/'/\\'/g;
426 16 push @arguments, qq($name='$value');
427 }
428 else {
429 50 push @arguments, $arg;
430 }
431 }
432 25 my $scen_str = join ' ', @arguments;
433  
434 # input data files can be specified in different ways
435 25 ▶ if ( $self->glob ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->glob) 2 23 25
436 2 my $mask = $self->glob;
437 2 $mask =~ s/^['"](.+)['"]$/$1/;
438 2 my @files = glob $mask;
439 2 ▶ log_fatal "No files matching mask $mask" if @files == 0;
Branch: 1 branch
BranchTrueFalseTotal
if @files == 0 0 2 2
440 2 $self->set_filenames( \@files );
441 }
442  
443 # some command line options are just shortcuts for blocks; the blocks are added to the scenario now
444 25 ▶ if ( $self->filenames ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->filenames) 10 15 25
445 10 my $reader = $self->_get_reader_name_for( @{ $self->filenames } );
446 10 log_info "Block $reader added to the beginning of the scenario.";
447 10 $scen_str = "$reader from=" . join( ',', @{ $self->filenames } ) . " $scen_str";
448 }
449  
450 25 ▶ if ( $self->save ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->save) 1 24 25
451 1 log_info "Block Write::Treex clobber=1 added to the end of the scenario.";
452 1 $scen_str .= ' Write::Treex clobber=1';
453 }
454  
455 25 ▶ if ( $self->lang ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->lang) 15 10 25
456 15 $scen_str = 'Util::SetGlobal language=' . $self->lang . " $scen_str";
457 }
458  
459 25 ▶ if ( $self->selector ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->selector) 0 25 25
460 0 $scen_str = 'Util::SetGlobal selector=' . $self->selector . " $scen_str";
461 }
462  
463 25 my $loading_started = time;
464 25 ▶ if ( $self->_has_scenario ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_has_scenario) { } 0 25 25
465 0 $self->scenario->restart();
466 }
467 else {
468 25 $self->set_scenario( Treex::Core::Scenario->new( from_string => $scen_str, runner => $self ) );
469 25 $self->scenario->load_blocks;
470 }
471 25 my $scenario = $self->scenario;
472 25 my $loading_ended = time;
473 25 log_info "Loading the scenario took " . ( $loading_ended - $loading_started ) . " seconds";
474  
475 25 my $number_of_docs;
476 25 ▶ if ( $self->jobindex ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->jobindex) 0 25 25
477 0 my $fn = $self->outdir . sprintf( "/job%03d.loaded", $self->jobindex );
478 0 ▶ open my $F, '>', $fn or log_fatal "Cannot open file $fn";
Branch: 1 branch
BranchTrueFalseTotal
open my $F, ">", $fn or log_fatal("Cannot open file $fn") 0 0 0
479 0 close $F;
480 0 my $reader = $scenario->document_reader;
481 0 $reader->set_jobs( $self->jobs );
482 0 $reader->set_jobindex( $self->jobindex );
483 0 $reader->set_outdir( $self->outdir );
484  
485 # If we know the number of documents in advance, inform the cluster head now
486 0 ▶ if ( $self->jobindex == 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->jobindex == 1) 0 0 0
487 0 $number_of_docs = $reader->number_of_documents;
488  
489 #log_info "There will be $number_of_docs documents";
490 0 $self->_write_total_doc_number($number_of_docs);
491 }
492 }
493  
494 25 $scenario->run();
495 25 log_info "Running the scenario took " . ( time - $loading_ended ) . " seconds";
496  
497 25 ▶ if ( $self->jobindex && $self->jobindex == 1 && !$number_of_docs ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->jobindex and $self->jobindex == 1 and not $number_of_docs) 0 25 25
Condition33%2/6
$self->jobindex and $self->jobindex == 1 and not $number_of_docs
!ll&&!rl&&r
2500
$self->jobindex and $self->jobindex == 1
!ll&&!rl&&r
2500
MC/DC0%0/3
$self->jobindex and $self->jobindex == 1 and not $number_of_docs
$self->jobindex $self->jobindex == 1 not $number_of_docs
Truth table25%1/4
A and B and not(C)
A= $self->jobindexB= $self->jobindex == 1C= not $number_of_docs
ABCresult
0XX0
10X0
1100
1111
498 0 $number_of_docs = $scenario->document_reader->doc_number;
499  
500 # This branch is executed only
501 # when the reader does not know number_of_documents in advance.
502 # TODO: Why is document_reader->doc_number is one higher than it should be?
503  
504 #log_info "There were $number_of_docs documents";
505 0 $self->_write_total_doc_number($number_of_docs);
506 }
507 25 return;
508 }
509  
510 # This is called by distributed jobs (they don't have $self->workdir)
511 sub _write_total_doc_number {
512 0 ▶ my ( $self, $number ) = @_;
Subroutine _write_total_doc_number: not called CC=2 SCAR=17.9
513 0 my $filename = $self->outdir . '/total_number_of_documents';
514 0 ▶ open my $F, '>', $filename or log_fatal $!;
Branch: 1 branch
BranchTrueFalseTotal
open my $F, ">", $filename or log_fatal($!) 0 0 0
515 0 print $F $number;
516 0 close $F;
517 0 return;
518 }
519  
520 # This is called by the main treex (it doesn't have $self->outdir)
521 sub _read_total_doc_number {
522 0 ▶ my ($self) = @_;
Subroutine _read_total_doc_number: not called CC=4 SCAR=30.0
523 0 my $total_doc_number_file = $self->workdir . "/output/total_number_of_documents";
524 0 ▶ if ( -f $total_doc_number_file ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $total_doc_number_file) { } 0 0 0
525 0 ▶ open( my $N, '<', $total_doc_number_file ) or log_fatal $!;
Branch: 1 branch
BranchTrueFalseTotal
open my $N, "<", $total_doc_number_file or log_fatal($!) 0 0 0
526 0 my $total_file_number = <$N>;
527 0 close $N;
528 0 ▶ if ( defined $total_file_number ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $total_file_number) 0 0 0
529 0 log_info "Total number of documents to be processed: $total_file_number";
530 }
531 0 return $total_file_number;
532 }
533 else {
534 0 return;
535 }
536 }
537  
538 sub _quote_argument {
539 0 ▶ my $arg = shift;
Subroutine _quote_argument: not called CC=1 SCAR=6.9
540 0 $arg =~ s/([\`\\\"\$])/\\$1/g;
541 0 return '"' . $arg . '"';
542 }
543  
544 sub _create_job_scripts {
545 0 ▶ my ($self) = @_;
Subroutine _create_job_scripts: not called CC=8 SCAR=42.8
546 0 my $current_dir = Cwd::cwd;
547 0 my $workdir = $self->workdir;
548  
549 # If there is some stdin piped to treex we must save it to a file
550 # and redirect it to the jobs.
551 # You cannot use interactive input from terminal to "treex -p".
552 # (If you really need it, use perl -npe 1 | treex -p ...)
553 0 my $input = '';
554 0 ▶ if ( !IO::Interactive::is_interactive(*STDIN) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (IO::Interactive::is_interactive(*STDIN)) 0 0 0
555 0 my $stdin_file = "$workdir/input";
556 0 $input = "cat $stdin_file | ";
557 ## no critic (ProhibitExplicitStdin)
558 0 ▶ open my $TEMP, '>', $stdin_file or log_fatal("Cannot create file $stdin_file to store input: $!");
Branch: 1 branch
BranchTrueFalseTotal
open my $TEMP, ">", $stdin_file or log_fatal("Cannot create file $stdin_file to store input: $!") 0 0 0
559 0 ▶ while (<STDIN>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline STDIN)) 0 0 0
560 0 print $TEMP $_;
561 }
562 0 close $TEMP;
563 }
564  
565 0 foreach my $jobnumber ( map { sprintf( "%03d", $_ ) } 1 .. $self->jobs ) {
566 0 my $script_filename = "scripts/job$jobnumber.sh";
567 0 ▶ open my $J, ">", "$workdir/$script_filename" or log_fatal $!;
Branch: 1 branch
BranchTrueFalseTotal
open my $J, ">", "$workdir/$script_filename" or log_fatal($!) 0 0 0
568 0 print $J "#!/bin/bash\n\n";
569 0 ▶ print $J 'echo -e "$HOSTNAME\n"`date +"%s"` > ' . ( $workdir =~ /^\// ? $workdir : "$current_dir/$workdir" )
Branch: 1 branch
BranchTrueFalseTotal
$workdir =~ m[^/] ? : 0 0 0
570 . "/output/job$jobnumber.started\n";
571 0 print $J "export PATH=/opt/bin/:\$PATH > /dev/null 2>&1\n\n";
572 0 print $J "cd $current_dir\n\n";
573 0 print $J "source " . Treex::Core::Config->lib_core_dir()
574 . "/../../../../config/init_devel_environ.sh 2> /dev/null\n\n"; # temporary hack !!!
575  
576 0 my $opts_and_scen = join ' ', map { _quote_argument($_) } @{ $self->ARGV };
577 0 ▶ if ( $self->filenames ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->filenames) 0 0 0
578 0 $opts_and_scen .= ' -- ' . join ' ', map { _quote_argument($_) } @{ $self->filenames };
579 }
580 0 print $J $input . "treex --jobindex=$jobnumber --workdir=$workdir --outdir=$workdir/output $opts_and_scen"
581 . " 2>> $workdir/output/job$jobnumber.started\n\n";
582 0 print $J "date +'%s' > $workdir/output/job$jobnumber.finished\n";
583 0 close $J;
584 0 chmod 0777, "$workdir/$script_filename";
585 }
586 0 return;
587 }
588  
589 sub _run_job_scripts {
590 0 ▶ my ($self) = @_;
Subroutine _run_job_scripts: not called CC=13 SCAR=52.0
591 0 my $workdir = $self->workdir;
592 0 ▶ if ( substr( $workdir, 0, 1 ) ne '/' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($workdir, 0, 1) ne "/") 0 0 0
593 0 $workdir = "./$workdir";
594 }
595 0 foreach my $jobnumber ( 1 .. $self->jobs ) {
596 0 my $script_filename = "scripts/job" . sprintf( "%03d", $jobnumber ) . ".sh";
597  
598 0 ▶ if ( $self->local ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->local) { } 0 0 0
599 0 system "$workdir/$script_filename &";
600 }
601 else {
602 0 my $mem = $self->mem;
603 0 my $qsub_opts = '-cwd -e output/ -S /bin/bash';
604 0 $qsub_opts .= " -hard -l mem_free=$mem -l act_mem_free=$mem -l h_vmem=$mem";
605 0 $qsub_opts .= ' -p ' . $self->priority;
606 0 $qsub_opts .= ' ' . $self->qsub;
607  
608 0 ▶ open my $QSUB, "cd $workdir && qsub $qsub_opts $script_filename |" or log_fatal $!; ## no critic (ProhibitTwoArgOpen)
Branch: 1 branch
BranchTrueFalseTotal
open my $QSUB, "cd $workdir && qsub $qsub_opts $script_filename |" or log_fatal($!) 0 0 0
609  
610 0 my $firstline = <$QSUB>;
611 0 close $QSUB;
612 0 ▶ chomp $firstline if ( defined $firstline );
Branch: 1 branch
BranchTrueFalseTotal
if defined $firstline 0 0 0
613 0 ▶ if ( defined $firstline && $firstline =~ /job (\d+)/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $firstline and $firstline =~ /job (\d+)/) { } 0 0 0
Condition0%0/3
defined $firstline and $firstline =~ /job (\d+)/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $firstline and $firstline =~ /job (\d+)/
defined $firstline $firstline =~ /job (\d+)/
Truth table0%0/3
A and B
A= defined $firstlineB= $firstline =~ /job (\d+)/
ABresult
0X0
100
111
614 0 push @{ $self->sge_job_numbers }, $1;
615 }
616 else {
617 0 log_fatal 'Job number not detected after the attempt at submitting the job. ' .
618 "Perhaps it was not possible to submit the job. See files in $workdir/output";
619 }
620 }
621 }
622 0 ▶ log_info $self->jobs . ' jobs '
Branch: 1 branch
BranchTrueFalseTotal
$self->local ? : 0 0 0
623 . ( $self->local ? 'executed locally.' : 'submitted to the cluster.' )
624 . ' Waiting for confirmation that they started...';
625 0 log_info( "Number of jobs started so far:", { same_line => 1 } );
626 0 my ( $started_now, $started_1s_ago ) = ( 0, 0 );
627 0 ▶ while ( $started_now != $self->jobs ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($started_now != $self->jobs) 0 0 0
628  
629 # $count = () = some_function();
630 # This is a Perl idiom (see e.g. page 32 of Modern Perl)
631 # for counting the number of elements returned by some_function()
632 # without using a temporary variable. It's useful when the function
633 # called in scalar context does not return the number of elements
634 # that would be returned when called in list context.
635 # And this is the case of glob which iterates in scalar context.
636 0 $started_now = () = glob $self->workdir . "/output/*.started";
637 0 ▶ if ( $started_now != $started_1s_ago ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($started_now != $started_1s_ago) { } 0 0 0
638 0 log_info( " $started_now", { same_line => 1 } );
639 0 $started_1s_ago = $started_now;
640 }
641 else {
642 0 sleep(1);
643 }
644 0 $self->_check_job_errors;
645 }
646 0 log_info "All " . $self->jobs . " jobs started. Waiting for loading scenarios...";
647  
648 0 log_info( "Number of jobs loaded so far:", { same_line => 1 } );
649 0 my ( $loaded_now, $loaded_1s_ago ) = ( 0, 0 );
650 0 ▶ while ( $loaded_now != $self->jobs ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($loaded_now != $self->jobs) 0 0 0
651 0 $loaded_now = () = glob $self->workdir . "/output/*.loaded";
652 0 ▶ if ( $loaded_now != $loaded_1s_ago ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($loaded_now != $loaded_1s_ago) { } 0 0 0
653 0 log_info( " $loaded_now", { same_line => 1 } );
654 0 $loaded_1s_ago = $loaded_now;
655 }
656 else {
657 0 sleep(1);
658 }
659 0 $self->_check_job_errors;
660 }
661 0 log_info "All " . $self->jobs . " jobs loaded. Waiting for them to be finished...";
662 0 return;
663 }
664  
665 # Prints error messages from the output of the current document processing.
666 sub _print_output_files {
667 0 ▶ my ( $self, $doc_number ) = @_;
Subroutine _print_output_files: not called CC=18 SCAR=58.3
668  
669 0 foreach my $stream (qw(stderr stdout)) {
670 0 my $job_number = $self->_get_job_number_from_doc_number($doc_number);
671  
672 0 my $filename = $self->workdir . "/output/job" . sprintf("%03d", $job_number ) . "-doc" . sprintf( "%07d", $doc_number ) . ".$stream";
673 0 log_info "Processing output file: " . $filename;
674  
675 0 ▶ if ( ! -f $filename ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $filename) 0 0 0
676 0 my $message = "Document $doc_number finished without producing $filename. " .
677 " It might be useful to inspect " . $self->workdir . "/output/job" . sprintf("%03d", $job_number ) . "-loading.stderr";
678 0 ▶ if ( $self->survive ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->survive) { } 0 0 0
679 0 log_warn("$message (fatal error ignored due to survival mode, be careful)");
680 0 return;
681 }
682 else {
683 0 log_fatal $message;
684 }
685 }
686  
687 # we have to wait until file is really written
688 0 my $wait_it = 0;
689 0 ▶ if ( -s $filename == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-s $filename == 0) 0 0 0
690 0 `touch $filename`;
691 }
692 #while ( -s $filename == 0 && $wait_it < 1 ) {
693 #
694 # print STDERR "Size: " . ( -s $filename) . "\n";
695 #open my $FILE, '<:encoding(utf8)', $filename;
696 #my $line = <$FILE>;
697 #close $FILE;
698 #log_info "File is still empty. " . $filename;
699 # Time::HiRes::usleep(300000);
700 # $wait_it++;
701 #}
702  
703 0 ▶ open my $FILE, '<:encoding(utf8)', $filename or log_fatal $!;
Branch: 1 branch
BranchTrueFalseTotal
open my $FILE, "<:encoding(utf8)", $filename or log_fatal($!) 0 0 0
704 0 ▶ if ( $stream eq "stdout" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stream eq 'stdout') { } 0 0 0
705 0 ▶ while (<$FILE>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline $FILE)) 0 0 0
706 0 print;
707 }
708 }
709 else {
710 0 my ($jobnumber) = ( $filename =~ /job(...)/ );
711 0 my $report = $self->forward_error_level;
712 0 my $success = 0;
713 0 ▶ while (<$FILE>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline $FILE)) 0 0 0
714  
715 # skip [success] indicatory lines, but set the success flag to 1
716 0 ▶ if ( $_ =~ /^Document [0-9]+\/[0-9\?]+ .*: \[success\]\.\r?\n?$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_ =~ m(^Document [0-9]+/[0-9\?]+ .*: \[success\]\.\r?\n?$)) 0 0 0
717 0 $success = 1;
718 0 next;
719 }
720  
721 #TODO: better implementation
722 # $Treex::Core::Log::ERROR_LEVEL_VALUE{$report} doesn't work
723 0 my ($level) = /^TREEX-(DEBUG|INFO|WARN|FATAL)/;
724 0 ▶ $level ||= '';
Condition0%0/2
$level ||= ""
l!l
00
MC/DC0%0/1
$level ||= ""
$level
Truth table0%0/2
A
A= $level
Aresult
11
00
725 0 ▶ next if $level =~ /^D/ && $report !~ /^[AD]/;
Branch: 1 branch
BranchTrueFalseTotal
if $level =~ /^D/ and not $report =~ /^[AD]/ 0 0 0
Condition0%0/3
$level =~ /^D/ and not $report =~ /^[AD]/
!ll&&!rl&&r
000
MC/DC0%0/2
$level =~ /^D/ and not $report =~ /^[AD]/
$level =~ /^D/ not $report =~ /^[AD]/
Truth table0%0/3
A and not(B)
A= $level =~ /^D/B= not $report =~ /^[AD]/
ABresult
0X0
100
111
726 0 ▶ next if $level =~ /^I/ && $report !~ /^[ADI]/;
Branch: 1 branch
BranchTrueFalseTotal
if $level =~ /^I/ and not $report =~ /^[ADI]/ 0 0 0
Condition0%0/3
$level =~ /^I/ and not $report =~ /^[ADI]/
!ll&&!rl&&r
000
MC/DC0%0/2
$level =~ /^I/ and not $report =~ /^[ADI]/
$level =~ /^I/ not $report =~ /^[ADI]/
Truth table0%0/3
A and not(B)
A= $level =~ /^I/B= not $report =~ /^[ADI]/
ABresult
0X0
100
111
727 0 ▶ next if $level =~ /^W/ && $report !~ /^[ADIW]/;
Branch: 1 branch
BranchTrueFalseTotal
if $level =~ /^W/ and not $report =~ /^[ADIW]/ 0 0 0
Condition0%0/3
$level =~ /^W/ and not $report =~ /^[ADIW]/
!ll&&!rl&&r
000
MC/DC0%0/2
$level =~ /^W/ and not $report =~ /^[ADIW]/
$level =~ /^W/ not $report =~ /^[ADIW]/
Truth table0%0/3
A and not(B)
A= $level =~ /^W/B= not $report =~ /^[ADIW]/
ABresult
0X0
100
111
728 0 print STDERR "job$jobnumber: $_";
729 }
730  
731 # test for the [success] indication on the last line of STDERR
732 0 ▶ if ( !$success ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($success) 0 0 0
733 0 log_fatal "Document $doc_number has not finished successfully (see $filename)";
734 }
735 }
736 0 close $FILE;
737 }
738 0 return;
739 }
740  
741 sub _doc_started {
742 0 ▶ my ( $self, $doc_number ) = @_;
Subroutine _doc_started: not called CC=1 SCAR=6.9
743 0 my $job_number = $self->_get_job_number_from_doc_number($doc_number);
744 0 my $filename = $self->workdir . sprintf( '/output/job%03d-doc%07d.stderr', $job_number, $doc_number );
745  
746 0 return -f $filename;
747 }
748  
749 sub _wait_for_jobs {
750 0 ▶ my ($self) = @_;
Subroutine _wait_for_jobs: not called CC=10 SCAR=47.0
751 0 my $current_doc_number = 1;
752 0 my $current_doc_started = 0;
753 0 my $total_doc_number = 0;
754 0 my $all_jobs_finished = 0;
755 0 my $done = 0;
756 0 my $jobs_finished = 1;
757  
758 0 my $glob_time = 0;
759 0 my $sleep_time = 0;
760 0 my $print_time = 0;
761  
762 0 my $wait_time = 1;
763  
764 0 ▶ while ( !$done ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($done) 0 0 0
765 0 ▶ $total_doc_number ||= $self->_read_total_doc_number();
Condition0%0/3
$total_doc_number ||= $self->_read_total_doc_number
l!l&&r!l&&!r
000
MC/DC0%0/2
$total_doc_number ||= $self->_read_total_doc_number
$total_doc_number $self->_read_total_doc_number
Truth table0%0/3
A ||= B
A= $total_doc_numberB= $self->_read_total_doc_number
ABresult
1X1
011
000
766  
767 # print STDERR "Fin: $all_jobs_finished; JobsFin: $jobs_finished; CurrD: $current_doc_number; TotD: $total_doc_number\n";
768 0 my $glob_start = Time::HiRes::time();
769  
770 0 ▶ if ( ! $all_jobs_finished ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($all_jobs_finished) 0 0 0
771 0 ▶ while ( -f $self->workdir . sprintf("/output/job%03d.finished", $jobs_finished) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $self->workdir . sprintf("/output/job%03d.finished", $jobs_finished)) 0 0 0
772 0 $jobs_finished++;
773 }
774 0 $all_jobs_finished = ( $jobs_finished > $self->jobs );
775 }
776 0 ▶ $current_doc_started ||= $self->_doc_started($current_doc_number);
Condition0%0/3
$current_doc_started ||= $self->_doc_started($current_doc_number)
l!l&&r!l&&!r
000
MC/DC0%0/2
$current_doc_started ||= $self->_doc_started($current_doc_number)
$current_doc_started $self->_doc_started($current_doc_number)
Truth table0%0/3
A ||= B
A= $current_doc_startedB= $self->_doc_started($current_doc_number)
ABresult
1X1
011
000
777  
778 0 $glob_time += (Time::HiRes::time() - $glob_start);
779  
780 # If a job starts processing another doc,
781 # it means it has finished the current doc.
782 0 my $current_doc_finished = $all_jobs_finished;
783 0 ▶ $current_doc_finished ||= $self->_doc_started( $current_doc_number + $self->jobs );
Condition0%0/3
$current_doc_finished ||= $self->_doc_started($current_doc_number + $self->jobs)
l!l&&r!l&&!r
000
MC/DC0%0/2
$current_doc_finished ||= $self->_doc_started($current_doc_number + $self->jobs)
$current_doc_finished $self->_doc_started($current_doc_number + $self->jobs)
Truth table0%0/3
A ||= B
A= $current_doc_finishedB= $self->_doc_started($current_doc_number + $self->jobs)
ABresult
1X1
011
000
784  
785 0 ▶ if ($current_doc_finished) {
Branch: 1 branch
BranchTrueFalseTotal
if ($current_doc_finished) { } 0 0 0
786 0 my $print_start = Time::HiRes::time();
787 0 $self->_print_output_files($current_doc_number);
788 0 $print_time += (Time::HiRes::time() - $print_start);
789 0 $current_doc_number++;
790 0 $current_doc_started = 0;
791 0 $wait_time = 1 + $total_doc_number / $current_doc_number;
792 0 ▶ if ( $wait_time > 120 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wait_time > 120) 0 0 0
793 0 $wait_time = 120;
794 }
795 }
796 else {
797 0 my $sleep_start = Time::HiRes::time();
798 0 sleep $wait_time;
799 0 $sleep_time += (Time::HiRes::time() - $sleep_start);
800 }
801  
802 0 $self->_check_job_errors;
803  
804 # Both of the conditions below are necessary.
805 # - $total_doc_number might be unknown (i.e. 0) before all_jobs_finished
806 # - even if all_jobs_finished, we must wait for forwarding all output files
807 # Note that if $current_doc_number == $total_doc_number,
808 # the output of the last doc was not forwarded yet.
809 0 ▶ $done = $all_jobs_finished && $current_doc_number > $total_doc_number;
Condition0%0/3
$all_jobs_finished && $current_doc_number > $total_doc_number
!ll&&!rl&&r
000
MC/DC0%0/2
$all_jobs_finished && $current_doc_number > $total_doc_number
$all_jobs_finished $current_doc_number > $total_doc_number
Truth table0%0/3
A && B
A= $all_jobs_finishedB= $current_doc_number > $total_doc_number
ABresult
0X0
100
111
810 }
811  
812 0 log_info "Glob Time: $glob_time";
813 0 log_info "Print Time: $print_time";
814 0 log_info "Sleep Time: $sleep_time";
815 0 return;
816 }
817  
818 sub _print_execution_time {
819 0 ▶ my ($self) = @_;
Subroutine _print_execution_time: not called CC=7 SCAR=40.3
820  
821 0 my $time_total = 0;
822  
823 0 my %hosts = ();
824  
825 # read job log files
826 0 for my $file_finished ( glob $self->workdir . "/output/job???.finished" ) {
827  
828 # derivate file name
829 0 my $file_started = $file_finished;
830 0 $file_started =~ s/finished/started/;
831  
832 # retrieve start time
833 0 ▶ open( my $fh_started, "<", $file_started ) or log_fatal $!;
Branch: 1 branch
BranchTrueFalseTotal
open my $fh_started, "<", $file_started or log_fatal($!) 0 0 0
834 0 my $hostname = <$fh_started>;
835 0 chomp $hostname;
836 0 my $time_start = <$fh_started>;
837 0 close($fh_started);
838  
839 # retrieve finish time
840 0 ▶ open( my $fh_finished, "<", $file_finished ) or log_fatal $!;
Branch: 1 branch
BranchTrueFalseTotal
open my $fh_finished, "<", $file_finished or log_fatal($!) 0 0 0
841 0 my $time_finish = <$fh_finished>;
842 0 close($fh_finished);
843  
844 # increase total time
845 0 $time_total += ( $time_finish - $time_start );
846 0 $hosts{$hostname}{'time'} += ( $time_finish - $time_start );
847 0 $hosts{$hostname}{'c'}++;
848 }
849  
850 # find the slowest and the fastest machine
851 0 my $min_time = $time_total;
852 0 my $min_host = "";
853 0 my $max_time = 0;
854 0 my $max_host = 0;
855  
856 0 for my $host ( keys %hosts ) {
857 0 my $avg = $hosts{$host}{'time'} / $hosts{$host}{'c'};
858 0 ▶ if ( $avg < $min_time ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($avg < $min_time) 0 0 0
859 0 $min_time = $avg;
860 0 $min_host = $host;
861 }
862  
863 0 ▶ if ( $avg > $max_time ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($avg > $max_time) 0 0 0
864 0 $max_time = $avg;
865 0 $max_host = $host;
866 }
867 }
868  
869 # print out statistics
870 0 log_info "Total execution time: $time_total";
871 0 log_info "Execution time per job: " . sprintf( "%0.3f", $time_total / $self->jobs );
872 0 log_info "Slowest machine: $max_host = $max_time";
873 0 log_info "Fastest machine: $min_host = $min_time";
874  
875 0 return;
876 }
877  
878 # To get utf8 encoding also when using qx (aka backticks):
879 # my $command_output = qw($command);
880 # we need to
881 28 ▶use open qw{ :std IO :encoding(UTF-8) };
Subroutine BEGIN: called CC=1 SCAR=0.0
882  
883 sub _check_job_errors {
884 0 ▶ my ($self) = @_;
Subroutine _check_job_errors: not called CC=3 SCAR=24.8
885 0 my $workdir = $self->workdir;
886 0 ▶ if ( defined( my $fatal_name = glob "$workdir/output/*fatalerror" ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $fatal_name = CORE::glob("$workdir/output/*fatalerror"))) 0 0 0
887 0 log_info "At least one job crashed with fatal error ($fatal_name).";
888 0 my ($fatal_job) = $fatal_name =~ /job(\d+)/;
889 0 my $command = "grep -h -A 10 -B 25 FATAL $workdir/output/job$fatal_job*.stderr";
890 0 my $fatal_lines = qx($command);
891 0 log_info "********************** FATAL ERRORS FOUND IN JOB $fatal_job ******************\n";
892 0 log_info "$fatal_lines\n";
893 0 log_info "********************** END OF JOB $fatal_job FATAL ERRORS LOG ****************\n";
894 0 ▶ if ( $self->survive ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->survive) { } 0 0 0
895 0 log_warn("fatal error ignored due to the --survive option, be careful");
896 0 return;
897 }
898 else {
899 0 log_info "All remaining jobs will be interrupted now.";
900 0 $self->_delete_jobs_and_exit;
901 }
902 }
903 0 return;
904 }
905  
906 sub _delete_jobs_and_exit {
907 0 ▶ my ($self) = @_;
Subroutine _delete_jobs_and_exit: not called CC=2 SCAR=17.9
908  
909 0 log_info "Deleting jobs: " . join( ', ', @{ $self->sge_job_numbers } );
910 0 foreach my $job ( @{ $self->sge_job_numbers } ) {
911 0 system "qdel $job";
912 }
913 0 log_info 'You may want to inspect generated files in ' . $self->workdir . '/output/';
914 0 exit;
915 }
916  
917 sub _execute_on_cluster {
918 0 ▶ my ($self) = @_;
Subroutine _execute_on_cluster: not called CC=8 SCAR=42.8
919  
920 # create working directory, if not specified as a command line option
921 0 ▶ if ( not defined $self->workdir ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->workdir) 0 0 0
922 0 my $counter;
923 my $directory_prefix;
924 0 my @existing_dirs;
925 0 ▶ do {
Branch: 1 branch
BranchTrueFalseTotal
@existing_dirs and do { do { ++$counter; $directory_prefix = sprintf("%03d-cluster-run-", $counter); @existing_dirs = CORE::glob("$directory_prefix*") } } 0 0 0
926 0 $counter++;
927 0 $directory_prefix = sprintf "%03d-cluster-run-", $counter;
928  
929 # TODO There is a strange problem when executing e.g.
930 # for i in `seq 4`; do treex/bin/t/qparallel.t; done
931 # where qparallel.t executes treex -p --cleanup ...
932 # I don't know the real cause of the bug, but as a workaround
933 # you can omit --cleanup or uncomment next line
934 # $directory .= sprintf "%03d-cluster-run", rand 1000;
935 # print STDERR "XXXX tested prefix $directory_prefix:".(join ' ', glob("$directory_prefix*"))."\n";
936 0 @existing_dirs = glob "$directory_prefix*"; # separate var because of troubles with glob context
937 }
938 while (@existing_dirs);
939 0 ▶ my $directory = tempdir "${directory_prefix}XXXXX" or log_fatal($!);
Branch: 1 branch
BranchTrueFalseTotal
my $directory = tempdir("${directory_prefix}XXXXX") or log_fatal($!) 0 0 0
940 0 $self->set_workdir($directory);
941 0 log_info "Working directory $directory created";
942  
943 # mkdir $directory or log_fatal $!;
944 }
945  
946 0 foreach my $subdir (qw(output scripts)) {
947 0 ▶ mkdir $self->workdir . "/$subdir" or log_fatal 'Could not create directory ' . $self->workdir . "/$subdir : " . $!;
Branch: 1 branch
BranchTrueFalseTotal
mkdir $self->workdir . "/$subdir" or log_fatal('Could not create directory ' . $self->workdir . "/$subdir : " . $!) 0 0 0
948 }
949  
950 # catching Ctrl-C interruption
951 local $SIG{INT} =
952 sub {
953 0 ▶ log_info "Caught Ctrl-C, all jobs will be interrupted";
Subroutine __ANON__: not called CC=1 SCAR=6.9
954 0 $self->_delete_jobs_and_exit();
955 0 };
956  
957 0 $self->_create_job_scripts();
958 0 $self->_run_job_scripts();
959  
960 0 STDOUT->autoflush(1);
961 0 STDERR->autoflush(1);
962  
963 0 $self->_wait_for_jobs();
964  
965 0 $self->_print_execution_time();
966  
967 0 log_info "All jobs finished.";
968  
969 0 ▶ if ( $self->cleanup ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->cleanup) 0 0 0
970 0 log_info "Deleting the directory with temporary files " . $self->workdir;
971 0 ▶ rmtree $self->workdir or log_fatal $!;
Branch: 1 branch
BranchTrueFalseTotal
rmtree($self->workdir) or log_fatal($!) 0 0 0
972 }
973 0 return;
974 }
975  
976 sub _redirect_output {
977 0 ▶ my ( $outdir, $docnumber, $jobindex ) = @_;
Subroutine _redirect_output: not called CC=6 SCAR=37.4
978 0 my $job = sprintf( 'job%03d', $jobindex + 0 );
979 0 ▶ my $doc = $docnumber ? sprintf( "doc%07d", $docnumber ) : 'loading';
Branch: 1 branch
BranchTrueFalseTotal
$docnumber ? : 0 0 0
980 0 my $stem = "$outdir/$job-$doc";
981 0 ▶ open my $OUTPUT, '>', "$stem.stdout" or log_fatal $!; # where will these messages go to, before redirection?
Branch: 1 branch
BranchTrueFalseTotal
open my $OUTPUT, ">", "$stem.stdout" or log_fatal($!) 0 0 0
982 0 ▶ open my $ERROR, '>', "$stem.stderr" or log_fatal $!;
Branch: 1 branch
BranchTrueFalseTotal
open my $ERROR, ">", "$stem.stderr" or log_fatal($!) 0 0 0
983 0 ▶ STDOUT->fdopen( $OUTPUT, 'w' ) or log_fatal $!;
Branch: 1 branch
BranchTrueFalseTotal
"STDOUT"->fdopen($OUTPUT, "w") or log_fatal($!) 0 0 0
984 0 ▶ STDERR->fdopen( $ERROR, 'w' ) or log_fatal $!;
Branch: 1 branch
BranchTrueFalseTotal
"STDERR"->fdopen($ERROR, "w") or log_fatal($!) 0 0 0
985 0 STDOUT->autoflush(1);
986  
987 # special file is touched if log_fatal is called
988 Treex::Core::Log::add_hook(
989 'FATAL',
990 sub {
991 0 ▶ eval { system qq(touch $stem.fatalerror) }; ## no critic (RequireCheckingReturnValueOfEval)
Subroutine __ANON__: not called CC=1 SCAR=6.9
992 }
993 0 );
994 0 return;
995 }
996  
997 sub _get_job_number_from_doc_number
998 {
999 0 ▶ my ($self, $doc_number) = @_;
Subroutine _get_job_number_from_doc_number: not called CC=1 SCAR=6.9
1000 0 return ( $doc_number - 1 ) % ($self->jobs) + 1;
1001 }
1002  
1003  
1004 # not a method !
1005 sub treex {
1006  
1007 # ref to array of arguments, or a string containing all arguments as on the command line
1008 31 ▶ my $arguments = shift;
Subroutine treex: called CC=7 SCAR=20.1
Pod documented
1009  
1010 31 ▶ if ( ref($arguments) eq 'ARRAY' && scalar @$arguments > 0 ) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $arguments eq 'ARRAY' and scalar @$arguments > 0) { } 27 4 31
elsif (defined $arguments and ref $arguments ne 'ARRAY') { } 4 0 4
Condition66%2/3
ref $arguments eq "ARRAY" and scalar @$arguments > 0
!ll&&!rl&&r
4027
MC/DC50%1/2
ref $arguments eq "ARRAY" and scalar @$arguments > 0
ref $arguments eq "ARRAY" scalar @$arguments > 0
Truth table66%2/3
A and B
A= ref $arguments eq "ARRAY"B= scalar @$arguments > 0
ABresult
0X0
100
111
1011 27 ▶ my $idx = first_index { $_ eq '--' } @$arguments;
Subroutine __ANON__: called CC=1 SCAR=0.0
1012 27 my %args = ( argv => $arguments );
1013 27 ▶ if ( $idx != -1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($idx != -1) 8 19 27
1014 8 $args{filenames} = [ splice @$arguments, $idx + 1 ];
1015 8 pop @$arguments; # delete "--"
1016 }
1017 27 my $runner = Treex::Core::Run->new_with_options( \%args );
1018 25 $runner->_execute();
1019  
1020 }
1021  
1022 ▶ elsif ( defined $arguments && ref($arguments) ne 'ARRAY' ) {
Condition33%1/3
defined $arguments and ref $arguments ne "ARRAY"
!ll&&!rl&&r
004
MC/DC0%0/2
defined $arguments and ref $arguments ne "ARRAY"
defined $arguments ref $arguments ne "ARRAY"
Truth table33%1/3
A and B
A= defined $argumentsB= ref $arguments ne "ARRAY"
ABresult
0X0
100
111
1023 4 ▶ treex( [ grep { defined $_ && $_ ne '' } split( /\s/, $arguments ) ] );
Branch: 1 branch
BranchTrueFalseTotal
defined $_ and $_ ne "" 28 0 28
1024 }
1025  
1026 else {
1027 0 treex('--help');
1028  
1029 #log_fatal 'Unspecified arguments for running treex.';
1030 }
1031 29 return;
1032 }
1033  
1034 28 1;
1035  
1036 __END__
1037  
1038 --watch option
1039  
1040 SYNOPSIS:
1041 touch timestamp.file
1042 treex --watch=timestamp.file my.scen & # or without & and open another terminal
1043 # after all documents are processed, treex is still running, watching timestamp.file
1044 # you can modify any modules/blocks and then
1045 touch timestamp.file
1046 # All modified modules will be reloaded (the number of reloaded modules is printed).
1047 # The document reader is restarted, so it starts reading the first file again.
1048 # To exit this "watching loop" either rm timestamp.file or press Ctrl^C.
1049  
1050 BENEFITS:
1051 * much faster development cycles (e.g. most time of en-cs translation is spent on loading)
1052 * Now I have some non-deterministic problems with loading NER::Stanford
1053 - using --watch I get it loaded on all jobs once and then I don't have to reload it.
1054  
1055 TODO:
1056 * modules are just reloaded, no constructors are called yet
1057  
1058  
1059 =for Pod::Coverage BUILD get_version
1060  
1061 =encoding utf-8
1062  
1063 =head1 NAME
1064  
1065 Treex::Core::Run + treex - applying Treex blocks and/or scenarios on data
1066  
1067 =head1 VERSION
1068  
1069 version 0.08633_1
1070  
1071 =head1 SYNOPSIS
1072  
1073 In bash:
1074  
1075 > treex myscenario.scen -- data/*.treex
1076 > treex My::Block1 My::Block2 -- data/*.treex
1077  
1078 In Perl:
1079  
1080 use Treex::Core::Run q(treex);
1081 treex([qw(myscenario.scen -- data/*.treex)]);
1082 treex([qw(My::Block1 My::Block2 -- data/*.treex)]);
1083  
1084 =head1 DESCRIPTION
1085  
1086 C<Treex::Core::Run> allows to apply a block, a scenario, or their mixture on a
1087 set of data files. It is designed to be used primarily from bash command line,
1088 using a thin front-end script called C<treex>. However, the same list of
1089 arguments can be passed by an array reference to the function C<treex()>
1090 imported from C<Treex::Core::Run>.
1091  
1092 Note that this module supports distributed processing, simply by adding switch
1093 C<-p>. Then there are two ways to process the data in a parallel fashion. By
1094 default, SGE cluster\'s C<qsub> is expected to be available. If you have no
1095 cluster but want to make the computation parallelized at least on a multicore
1096 machine, add the C<--local> switch.
1097  
1098 =head1 SUBROUTINES
1099  
1100 =over 4
1101  
1102 =item treex
1103  
1104 create new runner and runs scenario given in parameters
1105  
1106 =back
1107  
1108 =head1 USAGE
1109  
1110 usage: treex [-?dEegjLmpqSsv] [long options...] scenario [-- treex_files]
1111 scenario is a sequence of blocks or *.scen files
1112 options:
1113 -? --usage --help Prints this usage information.
1114 -s --save save all documents
1115 -q --quiet Warning, info and debug messages are
1116 suppressed. Only fatal errors are
1117 reported.
1118 --cleanup Delete all temporary files.
1119 -e --error_level Possible values: ALL, DEBUG, INFO, WARN,
1120 FATAL
1121 -E --forward_error_level messages with this level or higher will
1122 be forwarded from the distributed jobs
1123 to the main STDERR
1124 -L --language --lang shortcut for adding "Util::SetGlobal
1125 language=xy" at the beginning of the
1126 scenario
1127 -S --selector shortcut for adding "Util::SetGlobal
1128 selector=xy" at the beginning of the
1129 scenario
1130 -g --glob Input file mask whose expansion is to
1131 Perl, e.g. --glob '*.treex'
1132 -p --parallel Parallelize the task on SGE cluster
1133 (using qsub).
1134 -j --jobs Number of jobs for parallelization,
1135 default 10. Requires -p.
1136 --jobindex Not to be used manually. If number of
1137 jobs is set to J and modulo set to M,
1138 only I-th files fulfilling I mod J == M
1139 are processed.
1140 --outdir Not to be used manually. Dictory for
1141 collecting standard and error outputs in
1142 parallelized processing.
1143 --local Run jobs locally (might help with
1144 multi-core machines). Requires -p.
1145 --priority Priority for qsub, an integer in the
1146 range -1023 to 0 (or 1024 for admins),
1147 default=-100. Requires -p.
1148 --memory -m --mem How much memory should be allocated for
1149 cluster jobs, default=2G. Requires -p.
1150 Translates to "qsub -hard -l
1151 mem_free=$mem -l act_mem_free=$mem -l
1152 h_vmem=$mem".
1153 --qsub Additional parameters passed to qsub.
1154 Requires -p. See --priority and --mem.
1155 --watch re-run when the given file is changed
1156 TODO better doc
1157 --workdir working directory for temporary files in
1158 parallelized processing (if not
1159 specified, directories such as
1160 001-cluster-run, 002-cluster-run etc.
1161 are created)
1162 -d --dump_scenario Just dump (print to STDOUT) the given
1163 scenario and exit.
1164 --dump_required_files Just dump (print to STDOUT) files
1165 required by the given scenario and exit.
1166 --survive Continue collecting jobs' outputs even
1167 if some of them crashed (risky, use with
1168 care!).
1169 -v --version Print treex and perl version
1170  
1171 =head1 AUTHOR
1172  
1173 Zdeněk Žabokrtský <zabokrtsky@ufal.mff.cuni.cz>
1174  
1175 Martin Popel <popel@ufal.mff.cuni.cz>
1176  
1177 =head1 COPYRIGHT AND LICENSE
1178  
1179 Copyright © 2011 by Institute of Formal and Applied Linguistics, Charles University in Prague
1180  
1181 This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
« lib/Treex/Core/Resource.pm ↑ Summary lib/Treex/Core/DocumentReader/Base.pm »