Debian Codegraph @

lib/Test2/Harness/Collector.pm

raw
1 package Test2::Harness::Collector;
2 use strict;
3 use warnings;
4
5 our $VERSION = '1.000179';
6
7 use Carp qw/croak/;
8
9 use Test2::Harness::Collector::JobDir;
10
11 use Test2::Harness::Util::UUID qw/gen_uuid/;
12 use Test2::Harness::Util::Queue;
13 use Time::HiRes qw/sleep time/;
14 use File::Spec;
15
16 use File::Path qw/remove_tree/;
17
18 use Test2::Harness::Util::HashBase qw{
19 <run
20 <workdir
21 <run_id
22 <show_runner_output <truncate_runner_output <truncated_runner_output
23 <settings
24 <run_dir
25 <runner_pid +runner_exited <persistent_runner
26
27 <backed_up
28
29 +runner_stdout +runner_stderr +runner_aux_dir +runner_aux_handles
30
31 +task_file +task_queue +tasks_done +tasks
32 +jobs_file +jobs_queue +jobs_done +jobs
33 +pending
34
35 <wait_time <idle_wait
36 <action
37 };
38
39 # Floor of the idle backoff. The ceiling is 'wait_time'.
40 sub MIN_WAIT() { 0.001 }
41
42 sub init {
43 my $self = shift;
44
45 croak "'run' is required"
46 unless $self->{+RUN};
47
48 my $run_dir = File::Spec->catdir($self->{+WORKDIR}, $self->{+RUN_ID});
49 die "Could not find run dir" unless -d $run_dir;
50 $self->{+RUN_DIR} = $run_dir;
51
52 $self->{+WAIT_TIME} //= 0.02;
53 $self->{+IDLE_WAIT} = MIN_WAIT;
54
55 $self->{+ACTION}->($self->_harness_event(0, undef, time, harness_run => $self->{+RUN}, harness_settings => $self->settings, about => {no_display => 1}));
56 }
57
58 sub reset_idle_wait {
59 my $self = shift;
60 $self->{+IDLE_WAIT} = MIN_WAIT;
61 return;
62 }
63
64 # Sleep for the current backoff, then double it up to the 'wait_time' ceiling.
65 sub idle_sleep {
66 my $self = shift;
67
68 my $wait = $self->{+IDLE_WAIT};
69 sleep($wait);
70
71 $wait *= 2;
72 my $max = $self->{+WAIT_TIME};
73 $self->{+IDLE_WAIT} = $wait > $max ? $max : $wait;
74
75 return;
76 }
77
78 sub process {
79 my $self = shift;
80
81 my %warning_seen;
82 my $settings = $self->settings;
83
84 while (1) {
85 # $count is the liveness counter that guards loop exit: it also counts
86 # jobs that exist but have produced nothing yet. $work counts events
87 # actually processed, and is the only thing the sleep decision uses.
88 my $count = 0;
89 my $work = 0;
90 $work += $self->process_runner_output if $self->{+SHOW_RUNNER_OUTPUT};
91 $work += $self->process_tasks();
92 $count += $work;
93
94 # jobs() emits harness_job_start events for any newly discovered jobs;
95 # that counts as work. It cannot change $count: a new job means %$jobs
96 # is not empty, so the loop below counts it.
97 my $known = keys %{$self->{+JOBS} // {}};
98 my $jobs = $self->jobs;
99 $work += (keys %$jobs) - $known;
100
101 unless (keys %$jobs) {
102 if ($count) {
103 # Work was done, so do not sleep, but keep the backoff at its
104 # floor for the next idle iteration.
105 $self->reset_idle_wait;
106 next;
107 }
108
109 if ($self->persistent_runner) {
110 last if $self->{+JOBS_DONE};
111 last if $self->runner_done;
112 }
113
114 last if $self->runner_exited;
115 }
116
117 while(my ($job_try, $jdir) = each %$jobs) {
118 $count++;
119 my $e_count = 0;
120 for my $event ($jdir->poll($self->settings->collector->max_poll_events // 1000)) {
121 $self->{+ACTION}->($event);
122 $e_count++;
123 }
124
125 $count += $e_count;
126 $work += $e_count;
127 next if $e_count;
128 my $done = $jdir->done;
129 unless ($done) {
130 $count++;
131 next;
132 }
133
134 delete $jobs->{$job_try};
135 unless ($settings->debug->keep_dirs) {
136 my $job_path = $jdir->job_root;
137 # Needed because we set the perms so that a tmpdir under it can be used.
138 # This is the only remove_tree that needs it because it is the
139 # only one in a process that did not initially create the dir.
140 my $ok = eval {
141 chmod(0700, $job_path);
142 remove_tree($job_path, {safe => 1, keep_root => 0});
143 1;
144 };
145 my $err = $@;
146 unless ($ok) {
147 $count++;
148 unless ($warning_seen{$job_path}++) {
149 my $msg = "NON-FATAL Error deleting job dir ($job_path) will try again...: $err";
150 my $e = $self->_harness_event(0, undef, time, info => [{details => $msg, tag => "INTERNAL", debug => 1, important => 1}]);
151 $self->{+ACTION}->($e);
152 }
153 next;
154 }
155 }
156
157 delete $jobs->{$job_try};
158 delete $self->{+PENDING}->{$jdir->job_id} unless $done->{retry};
159 }
160
161 last if !$count && $self->runner_exited;
162
163 $work ? $self->reset_idle_wait : $self->idle_sleep;
164 }
165
166 # One last slurp
167 $self->process_runner_output if $self->{+SHOW_RUNNER_OUTPUT};
168
169 $self->{+ACTION}->(undef) if $self->{+JOBS_DONE} && $self->{+TASKS_DONE};
170
171 remove_tree($self->{+RUN_DIR}, {safe => 1, keep_root => 0}) unless $settings->debug->keep_dirs;
172
173 return;
174 }
175
176 sub runner_done {
177 my $self = shift;
178
179 return 0 if keys %{$self->{+PENDING}};
180 return 1;
181 }
182
183 sub runner_exited {
184 my $self = shift;
185 my $pid = $self->{+RUNNER_PID} or return undef;
186
187 return $self->{+RUNNER_EXITED} if $self->{+RUNNER_EXITED};
188
189 return 0 if kill(0, $pid);
190
191 return $self->{+RUNNER_EXITED} = 1;
192 }
193
194 sub process_runner_output {
195 my $self = shift;
196
197 my $out = 0;
198 return $out unless $self->{+SHOW_RUNNER_OUTPUT};
199
200 my $action = $self->{+ACTION};
201 if ($self->{+TRUNCATE_RUNNER_OUTPUT} && !$self->{+TRUNCATED_RUNNER_OUTPUT}) {
202 $action = sub {};
203 $self->{+TRUNCATED_RUNNER_OUTPUT} = 1;
204 }
205
206 my $stdout = $self->{+RUNNER_STDOUT} //= Test2::Harness::Util::File::Stream->new(
207 name => File::Spec->catfile($self->{+WORKDIR}, 'output.log'),
208 );
209
210 for my $line ($stdout->poll()) {
211 chomp($line);
212 my $e = $self->_harness_event(0, undef, time, info => [{details => $line, tag => 'INTERNAL', important => 1}]);
213 $action->($e);
214 $out++;
215 }
216
217 my $stderr = $self->{+RUNNER_STDERR} //= Test2::Harness::Util::File::Stream->new(
218 name => File::Spec->catfile($self->{+WORKDIR}, 'error.log'),
219 );
220
221 for my $line ($stderr->poll()) {
222 chomp($line);
223 my $e = $self->_harness_event(0, undef, time, info => [{details => $line, tag => 'INTERNAL', debug => 1, important => 1}]);
224 $action->($e);
225 $out++;
226 }
227
228 my $auxdir = $self->{+RUNNER_AUX_DIR} //= File::Spec->catdir($self->{+WORKDIR}, 'aux_logs');
229 return $out unless -d $auxdir;
230
231 opendir(my $dh, $auxdir) or die "Could not open aux_logs dir: $!";
232 for my $path (readdir($dh)) {
233 next if $path =~ m/^\.+$/;
234 next if $self->{+RUNNER_AUX_HANDLES}->{$path};
235
236 my $tag = uc($path);
237 next unless $tag =~ s/\.LOG$//;
238
239 my $debug = 0;
240 if ($tag =~ s/\W*(STDERR|STDOUT)\W*//g) {
241 $debug = 1 if $1 && uc($1) eq 'STDERR';
242 }
243
244 $self->{+RUNNER_AUX_HANDLES}->{$path} = {
245 tag => $tag,
246 debug => $debug,
247 stream => Test2::Harness::Util::File::Stream->new(name => File::Spec->catfile($auxdir, $path)),
248 };
249 }
250 closedir($dh);
251
252 for my $file (sort keys %{$self->{+RUNNER_AUX_HANDLES}}) {
253 my $data = $self->{+RUNNER_AUX_HANDLES}->{$file};
254 my $stream = $data->{stream};
255
256 for my $line ($stream->poll()) {
257 chomp($line);
258 my $e = $self->_harness_event(0, undef, time, info => [{details => $line, tag => $data->{tag}, debug => $data->{debug}, important => 1}]);
259 $action->($e);
260 $out++;
261 }
262 }
263
264 return $out;
265 }
266
267 sub process_tasks {
268 my $self = shift;
269
270 return 0 if $self->{+TASKS_DONE};
271
272 my $queue = $self->tasks_queue or return 0;
273
274 my $count = 0;
275 for my $item ($queue->poll) {
276 $count++;
277 my ($spos, $epos, $task) = @$item;
278
279 unless ($task) {
280 $self->{+TASKS_DONE} = 1;
281 last;
282 }
283
284 my $job_id = $task->{job_id} or die "No job id!";
285 $self->{+TASKS}->{$job_id} = $task;
286 $self->{+PENDING}->{$job_id} = 1 + ($task->{retry} || $self->run->retry || 0);
287
288 my $e = $self->_harness_event($job_id, $task->{is_try} // 0, $task->{stamp}, 'harness_job_queued' => $task);
289 $self->{+ACTION}->($e);
290 }
291
292 return $count;
293 }
294
295 sub send_backed_up {
296 my $self = shift;
297 return if $self->{+BACKED_UP}++;
298
299 # This is an unlikely code path. If we're here, it means the last loop couldn't process any results.
300 my $e = $self->_harness_event(0, undef, time, info => [{details => <<" EOT", tag => "INTERNAL", debug => 1, important => 1}]);
301 *** THIS IS NOT FATAL ***
302
303 * The collector has reached the maximum number of concurrent jobs to process.
304 * Testing will continue, but some tests may be running or even complete before they are rendered.
305 * All tests and events will eventually be displayed, and your final results will not be effected.
306
307 Set a higher --max-open-jobs collector setting to prevent this problem in the
308 future, but be advised that could result in too many open filehandles on some
309 systems.
310
311 This message will only be shown once.
312 EOT
313
314 $self->{+ACTION}->($e);
315 return;
316 }
317
318 sub jobs {
319 my $self = shift;
320
321 my $jobs = $self->{+JOBS} //= {};
322
323 return $jobs if $self->{+JOBS_DONE};
324
325 # Don't monitor more than 'max_open_jobs' or we might have too many open file handles and crash
326 # Max open files handles on a process applies. Usually this is 1024 so we
327 # can't have everything open at once when we're behind.
328 my $max_open_jobs = $self->settings->collector->max_open_jobs // 1024;
329 my $additional_jobs_to_parse = $max_open_jobs - keys %$jobs;
330 if($additional_jobs_to_parse <= 0) {
331 $self->send_backed_up;
332 return $jobs;
333 }
334
335 my $queue = $self->jobs_queue or return $jobs;
336
337 for my $item ($queue->poll($additional_jobs_to_parse)) {
338 my ($spos, $epos, $job) = @$item;
339
340 unless ($job) {
341 $self->{+JOBS_DONE} = 1;
342 last;
343 }
344
345 my $job_id = $job->{job_id} or die "No job id!";
346
347 die "Found job without a task!" unless $self->{+TASKS}->{$job_id};
348
349 $self->{+PENDING}->{$job_id}--;
350 delete $self->{+PENDING}->{$job_id} if $self->{+PENDING}->{$job_id} < 1;
351
352 my $file = $job->{file};
353 my $e = $self->_harness_event(
354 $job_id,
355 $job->{is_try},
356 $job->{stamp},
357 harness_job => $job,
358 harness_job_start => {
359 details => "Job $job_id started at $job->{stamp}",
360 job_id => $job_id,
361 stamp => $job->{stamp},
362 file => $file,
363 rel_file => File::Spec->abs2rel($file),
364 abs_file => File::Spec->rel2abs($file),
365 },
366 harness_job_launch => {
367 stamp => $job->{stamp},
368 retry => $job->{is_try},
369 },
370 );
371
372 $self->{+ACTION}->($e);
373
374 my $job_try = $job_id . '+' . $job->{is_try};
375
376 $jobs->{$job_try} = Test2::Harness::Collector::JobDir->new(
377 job_try => $job->{is_try} // 0,
378 job_id => $job_id,
379 run_id => $self->{+RUN_ID},
380 runner_pid => $self->{+RUNNER_PID},
381 job_root => File::Spec->catdir($self->{+RUN_DIR}, $job_try),
382 );
383 }
384
385 # The collector didn't read in all the jobs because it'd run out of file handles. We need to let the stream know we're behind.
386 $self->send_backed_up if $max_open_jobs <= keys %$jobs;
387
388 return $jobs;
389 }
390
391 sub _harness_event {
392 my $self = shift;
393 my ($job_id, $job_try, $stamp, %args) = @_;
394
395 croak "Job id is required" unless defined $job_id;
396 croak "Stamp is required" unless defined $stamp;
397
398 return Test2::Harness::Event->new(
399 stamp => $stamp,
400 job_id => $job_id,
401 job_try => $job_try,
402 event_id => gen_uuid(),
403 run_id => $self->{+RUN_ID},
404 facet_data => \%args,
405 );
406 }
407
408 sub jobs_queue {
409 my $self = shift;
410
411 return $self->{+JOBS_QUEUE} if $self->{+JOBS_QUEUE};
412
413 my $jobs_file = $self->{+JOBS_FILE} //= File::Spec->catfile($self->{+RUN_DIR}, 'jobs.jsonl');
414
415 return unless -f $jobs_file;
416
417 return $self->{+JOBS_QUEUE} = Test2::Harness::Util::Queue->new(file => $jobs_file);
418 }
419
420 sub tasks_queue {
421 my $self = shift;
422
423 return $self->{+TASK_QUEUE} if $self->{+TASK_QUEUE};
424
425 my $tasks_file = $self->{+TASK_FILE} //= File::Spec->catfile($self->{+RUN_DIR}, 'queue.jsonl');
426
427 return unless -f $tasks_file;
428
429 return $self->{+TASK_QUEUE} = Test2::Harness::Util::Queue->new(file => $tasks_file);
430 }
431
432 1;
433
434 __END__
435
436 =pod
437
438 =encoding UTF-8
439
440 =head1 NAME
441
442 Test2::Harness::Collector - Module that collects test output and provides it as
443 an event stream.
444
445 =head1 DESCRIPTION
446
447 This module is responsible for reading and parsing the output produced by
448 multiple jobs running under yath.
449
450 This module is not intended for external use, it is an implementation detail
451 and can change at any time. Currently instances of this module are not passed
452 to any plugins or callbacks.
453
454 If you need a collector for a third-party command you should look at
455 L<App::Yath::Command::collector>. When a command needs a collector (such as
456 L<App::Yath::Command::test> does) it normally spawns a collector process by
457 executing C<yath collector>. The C<start_collector()> subroutine in
458 L<App::Yath::Command::test> is a good place to look for more details.
459
460 =head1 SOURCE
461
462 The source code repository for Test2-Harness can be found at
463 F<http://github.com/Test-More/Test2-Harness/>.
464
465 =head1 MAINTAINERS
466
467 =over 4
468
469 =item Chad Granum E<lt>[email protected]<gt>
470
471 =back
472
473 =head1 AUTHORS
474
475 =over 4
476
477 =item Chad Granum E<lt>[email protected]<gt>
478
479 =back
480
481 =head1 COPYRIGHT
482
483 Copyright 2020 Chad Granum E<lt>[email protected]<gt>.
484
485 This program is free software; you can redistribute it and/or
486 modify it under the same terms as Perl itself.
487
488 See F<http://dev.perl.org/licenses/>
489
490 =cut