Debian Codegraph @

lib/Test2/Harness/Runner.pm

raw
1 package Test2::Harness::Runner;
2 use strict;
3 use warnings;
4
5 our $VERSION = '1.000179';
6
7 use File::Spec();
8
9 use Carp qw/confess croak/;
10 use Fcntl qw/LOCK_EX LOCK_UN/;
11 use POSIX qw/:sys_wait_h/;
12 use Long::Jump qw/setjump longjump/;
13 use Time::HiRes qw/sleep time/;
14 use Scope::Guard;
15
16 use Test2::Harness::Util qw/clean_path file2mod lock_file mod2file open_file parse_exit unlock_file write_file_atomic process_includes chmod_tmp write_file/;
17 use Test2::Harness::Util::Queue();
18 use Test2::Harness::Util::JSON(qw/encode_json/);
19
20 use Test2::Harness::Runner::Constants;
21
22 use Test2::Harness::Runner::Run();
23 use Test2::Harness::Runner::Job();
24 use Test2::Harness::Runner::Spawn();
25 use Test2::Harness::Runner::State();
26 use Test2::Harness::Runner::Preload();
27 use Test2::Harness::Runner::Preloader();
28 use Test2::Harness::Runner::Preloader::Stage();
29 use Test2::Harness::Runner::DepTracer();
30
31 use parent 'Test2::Harness::IPC';
32 use Test2::Harness::Util::HashBase(
33 # Fields from settings
34 qw{
35 <job_count <slots_per_job
36
37 <includes <tlib <lib <blib
38 <unsafe_inc
39
40 <use_fork <preloads <preload_threshold <switches
41 <restrict_reload
42
43 <cover
44
45 <event_timeout <post_exit_timeout <resource_timeout
46
47 <resources
48
49 <nytprof
50
51 <reload
52 },
53 # From Construction
54 qw{
55 <dir <settings <fork_job_callback <fork_spawn_callback <respawn_runner_callback <monitor_preloads
56 <jobs_todo <dump_depmap
57 },
58 # Other
59 qw {
60 +preloader
61 +state
62
63 <stage
64 <signal
65
66 +last_timeout_check
67 +dispatch_lock_file
68 +can_stage
69 <tmp_dir
70
71 <rootpid
72 <scheduler_pid
73 },
74 );
75
76 sub job_class { 'Test2::Harness::Runner::Job' }
77
78 our $RUNNER_PID;
79 sub init {
80 my $self = shift;
81
82 $self->{+ROOTPID} = $$;
83 $RUNNER_PID = $$;
84
85 croak "'dir' is a required attribute" unless $self->{+DIR};
86 croak "'settings' is a required attribute" unless $self->{+SETTINGS};
87
88 my $dir = clean_path($self->{+DIR});
89
90 croak "'$dir' is not a valid directory"
91 unless -d $dir;
92
93 $self->{+DIR} = $dir;
94
95 $self->{+HANDLERS}->{HUP} = sub {
96 my $sig = shift;
97 print "$$ $0 ($self->{+STAGE}) Runner caught SIG$sig, reloading...\n";
98 $self->{+SIGNAL} = $sig;
99 };
100
101 my $tmp_dir = File::Spec->catdir($self->{+DIR}, 'tmp');
102 unless (-d $tmp_dir) {
103 mkdir($tmp_dir) or die "Could not create temp dir: $!";
104 chmod_tmp($tmp_dir);
105 }
106 $self->{+TMP_DIR} = $tmp_dir;
107
108 my $have_job_limiter = 0;
109 for my $res (@{$self->{+RESOURCES}}) {
110 require(mod2file($res)) unless ref($res);
111 $have_job_limiter++ if $res->job_limiter;
112 }
113
114 unless ($have_job_limiter) {
115 require Test2::Harness::Runner::Resource::JobCount;
116 unshift @{$self->{+RESOURCES}} => 'Test2::Harness::Runner::Resource::JobCount';
117 }
118
119 $self->SUPER::init();
120 }
121
122 sub preloader {
123 my $self = shift;
124
125 $self->{+PRELOADER} //= Test2::Harness::Runner::Preloader->new(
126 dir => $self->{+DIR},
127 preloads => $self->preloads,
128 monitor => $self->{+MONITOR_PRELOADS},
129 restrict_reload => $self->{+RESTRICT_RELOAD},
130 dump_depmap => $self->{+DUMP_DEPMAP},
131 reload => $self->{+RELOAD},
132
133 below_threshold => ($self->{+PRELOAD_THRESHOLD} && $self->{+JOBS_TODO} && $self->{+PRELOAD_THRESHOLD} > $self->{+JOBS_TODO}) ? 1 : 0,
134 );
135 }
136
137 sub state {
138 my $self = shift;
139
140 my $preloader = $self->preloader;
141
142 my $settings = $self->settings;
143 $self->{+STATE} //= Test2::Harness::Runner::State->new(
144 workdir => $self->{+DIR},
145 eager_stages => $preloader->eager_stages // {},
146 preloader => $preloader,
147 resources => [map { $_->new(settings => $settings) } @{$self->{+RESOURCES}}],
148 settings => $settings,
149 );
150 }
151
152 sub check_timeouts {
153 my $self = shift;
154
155 return unless $self->settings->runner->use_timeout;
156
157 my $now = time;
158
159 # Check only once per second, that is as granular as we get. Also the check is not cheep.
160 return if $self->{+LAST_TIMEOUT_CHECK} && $now < (1 + $self->{+LAST_TIMEOUT_CHECK});
161
162 for my $pid (keys %{$self->{+PROCS}}) {
163 my $job = $self->{+PROCS}->{$pid};
164 next unless $job->isa('Test2::Harness::Runner::Job');
165 next unless $job->use_timeout;
166
167 my $et = $job->event_timeout // $self->{+EVENT_TIMEOUT};
168 my $pet = $job->post_exit_timeout // $self->{+POST_EXIT_TIMEOUT};
169
170 next unless $et || $pet;
171
172 my $changed = $job->output_changed();
173 my $delta = $now - $changed;
174
175 # Event timout if we are checking for one, and if the delta is larger than the timeout.
176 my $e_to = $et && $delta > $et;
177
178 # Post-Exit timeout if we are checking for one, the process has exited (we are waiting) and the delta is larger than the timeout.
179 my $pe_to = $pet && $self->{+WAITING}->{$pid} && $delta > $pet;
180
181 next unless $e_to || $pe_to;
182
183 my $kill = -f $job->et_file || -f $job->pet_file;
184
185 write_file_atomic($job->et_file, "$now $delta") if $e_to && !-f $job->et_file;
186 write_file_atomic($job->pet_file, "$now $delta") if $pe_to && !-f $job->pet_file;
187
188 my $sigmap = $self->SIG_MAP;
189 my $sig = $kill ? $sigmap->{'KILL'} : $sigmap->{'TERM'};
190
191 $sig = "-$sig" if $self->USE_P_GROUPS;
192
193 print STDERR "$$ $0 " . $job->file . " did not respond to SIGTERM, sending SIGKILL to $pid...\n" if $kill;
194
195 # storing the jobid we had to stop
196 $self->{run_reached_timeout} //= {};
197 $self->{run_reached_timeout}->{$job->task->{job_id}} = $pid;
198
199 kill($sig, $pid);
200 }
201
202 $self->{+LAST_TIMEOUT_CHECK} = time;
203 }
204
205 sub stop {
206 my $self = shift;
207
208 $self->check_for_fork;
209
210 if (keys %{$self->{+PROCS}}) {
211 print "$$ $0 Sending all child processes the TERM signal...\n";
212 # Send out the TERM signal
213 $self->killall($self->{+SIGNAL} // 'TERM');
214 $self->wait(all => 1, timeout => 5);
215 }
216
217 # Time to get serious
218 if (keys %{$self->{+PROCS}}) {
219 local $?;
220 print STDERR "$$ $0 Some child processes are refusing to exit, sending KILL signal...\n";
221 print("$$ $0 == $_ " . waitpid($_, WNOHANG) . "\n") for keys %{$self->{+PROCS}};
222 $self->killall('KILL');
223 }
224
225 $self->SUPER::stop();
226 }
227
228 sub dispatch_lock_file {
229 my $self = shift;
230 return $self->{+DISPATCH_LOCK_FILE} //= File::Spec->catfile($self->{+DIR}, 'dispatch.lock');
231 }
232
233 sub handle_sig {
234 my $self = shift;
235 my ($sig) = @_;
236
237 return if $self->{+SIGNAL};
238
239 return $self->{+HANDLERS}->{$sig}->($sig) if $self->{+HANDLERS}->{$sig};
240
241 $self->{+SIGNAL} = $sig;
242 die "Runner caught SIG$sig. Attempting to shut down cleanly...\n";
243 }
244
245 sub all_libs {
246 my $self = shift;
247
248 my @out;
249
250 push @out => @{$self->{+INCLUDES}} if $self->{+INCLUDES};
251
252 push @out => 't/lib' if $self->{+TLIB};
253 push @out => 'lib' if $self->{+LIB};
254
255 if ($self->{+BLIB}) {
256 push @out => 'blib/lib';
257 push @out => 'blib/arch';
258 }
259
260 return @out;
261 }
262
263 sub process {
264 my $self = shift;
265
266 @INC = process_includes(
267 list => [@{$self->settings->harness->dev_libs}, $self->all_libs],
268 include_dot => $self->unsafe_inc,
269 include_current => 1,
270 clean => 1,
271 );
272
273 my $pidfile = File::Spec->catfile($self->{+DIR}, 'PID');
274 write_file_atomic($pidfile, "$$");
275
276 $self->start();
277
278 my $ok = eval { $self->run_tests(); 1 };
279 my $err = $@;
280 $self->{+CAN_STAGE} = 0;
281
282 warn $err unless $ok;
283
284 $self->stop();
285
286 return $self->{+SIGNAL} ? 128 + $self->SIG_MAP->{$self->{+SIGNAL}} : $ok ? 0 : 1;
287 }
288
289 sub spawn_scheduler {
290 my $self = shift;
291
292 return unless $self->{+ROOTPID} == $$;
293
294 my $pid = fork // die "Could not fork: $!";
295 if ($pid) {
296 $self->{+SCHEDULER_PID} = $pid;
297 return $self->watch_pid($pid);
298 }
299
300 setpgrp(0, 0) if Test2::Harness::Util::IPC::USE_P_GROUPS();
301
302 my $guard = Scope::Guard->new(sub {
303 my $err = $@;
304 print STDERR "\n\n$$ $0 Scheduler escaped scope!\n";
305 print STDERR "$$ $0 Error: $err\n" if $err;
306 exit 255;
307 });
308
309 $0 =~ s/-runner/-scheduler/i;
310
311 my $state = $self->state;
312
313 my $lock = open_file($self->dispatch_lock_file, '>>');
314
315 my $consecutive_errors = 0;
316 my $max_errors = 5;
317
318 while (1) {
319 my $ok = eval {
320 $state->poll;
321
322 # Retrying form: a stall report sends SIGUSR1, and flock is not
323 # restarted after a handler runs, so a plain 'or die' here would
324 # report a scheduler error that never happened.
325 lock_file($lock);
326
327 while (1) {
328 next if $state->advance;
329 last;
330 }
331
332 unlock_file($lock);
333
334 if (my $idle = $state->resource_timeout($self->{+RESOURCE_TIMEOUT})) {
335 print STDERR "\n\nyath: Resource timeout after ${idle}s with no tests able to start. Aborting.\n";
336 print STDERR "There are pending tests but resources have not become available.\n";
337 print STDERR "Use --resource-timeout to adjust or disable (0) this timeout.\n\n";
338 $state->truncate();
339 $self->{+SIGNAL} = 'TERM';
340 }
341
342 1;
343 };
344
345 unless ($ok) {
346 my $err = $@;
347 $consecutive_errors++;
348 eval { flock($lock, LOCK_UN) };
349 print STDERR "\n$$ $0 Scheduler error ($consecutive_errors/$max_errors): $err\n";
350
351 if ($consecutive_errors >= $max_errors) {
352 print STDERR "$$ $0 Scheduler aborting after $consecutive_errors consecutive errors.\n";
353 $guard->dismiss;
354 exit 255;
355 }
356 }
357 else {
358 $consecutive_errors = 0;
359 }
360
361 if ($self->end_test_loop()) {
362 $guard->dismiss;
363 exit(0);
364 }
365
366 my $slept = 0;
367 if ($self->{+WAIT_TIME}) {
368 # This sleep is often interrupted by signals.
369 while ($slept < $self->{+WAIT_TIME}) {
370 $slept += sleep($self->{+WAIT_TIME} - $slept);
371 }
372 }
373 }
374
375 warn "$$ $0 Escaped scheduler loop";
376 exit 255;
377 }
378
379 sub run_tests {
380 my $self = shift;
381
382 my $preloader = $self->preloader;
383 $preloader->preload();
384
385 $self->spawn_scheduler();
386
387 my ($stage, @procs) = $preloader->preload_stages();
388
389 if ($self->dump_depmap) {
390 if (my $dtrace = $preloader->dtrace) {
391 if (my $depmap = $dtrace->dep_map) {
392 my $file = "depmap-$stage.json";
393 write_file($file, encode_json($depmap));
394 }
395 }
396 }
397
398 $self->watch($_) for @procs;
399
400 while(1) {
401 $self->{+CAN_STAGE} = 1;
402 my $jump = setjump "Stage-Runner" => sub {
403 $self->run_stage($stage);
404 };
405
406 last unless $jump;
407
408 ($stage) = @$jump;
409 $self->reset_stage();
410 }
411
412 return;
413 }
414
415 sub reset_stage {
416 my $self = shift;
417
418 # Normalize IPC
419 $self->check_for_fork();
420
421 # If no stage was set we do not want to clear this, root stages need to
422 # preserve the preloads
423 return unless $self->{+STAGE};
424
425 # From Runner
426 delete $self->{+STAGE};
427 delete $self->{+STATE};
428 delete $self->{+LAST_TIMEOUT_CHECK};
429
430 return;
431 }
432
433 sub run_stage {
434 my $self = shift;
435 my ($stage) = @_;
436
437 $self->{+STAGE} = $stage;
438 $self->state->stage_ready($stage);
439
440 while (1) {
441 next if $self->run_job();
442
443 next if $self->wait();
444
445 last if $self->end_test_loop();
446
447 sleep($self->{+WAIT_TIME}) if $self->{+WAIT_TIME};
448 }
449
450 $self->state->stage_down($stage);
451
452 $self->killall($self->{+SIGNAL}) if $self->{+SIGNAL};
453
454 $self->wait(all => 1);
455
456 exit 0 unless $stage eq 'base' || $stage eq 'default';
457 }
458
459 sub run_job {
460 my $self = shift;
461
462 my $task = $self->state->next_task($self->{+STAGE}) or return 0;
463
464 if ($task->{spawn} && !$task->{resource_skip}) {
465 my $job = Test2::Harness::Runner::Spawn->new(
466 runner => $self,
467 task => $task,
468 settings => $self->settings,
469 fork_callback => $self->{+FORK_SPAWN_CALLBACK},
470 );
471
472 $self->{+FORK_SPAWN_CALLBACK}->($self, $job);
473 return 1;
474 }
475
476 my $run = $self->state->run();
477 return 1 unless $run;
478
479 my $job_class;
480 if ($task->{job_class}) {
481 $job_class = $task->{job_class};
482 require(mod2file($job_class));
483
484 die "Custom job class $job_class overrode the category, this is a fatal mistake"
485 unless $job_class->category eq $self->job_class->category;
486 }
487 else {
488 $job_class = $self->job_class;
489 }
490
491 my $job = $job_class->new(
492 runner => $self,
493 task => $task,
494 run => $run,
495 settings => $self->settings,
496 fork_callback => $self->{+FORK_JOB_CALLBACK},
497 );
498
499 $job->prepare_dir();
500
501 my $spawn_time;
502
503 my $pid;
504 my $via = $job->via();
505 if ($via) {
506 require(mod2file($1)) if !defined(&{$via}) && $via =~ m/^(.+)::[^:]+$/;
507
508 $spawn_time = time();
509 $pid = $self->$via($job);
510 $job->set_pid($pid);
511 $self->watch($job);
512 }
513 else {
514 $spawn_time = time();
515 $self->spawn($job);
516 $pid = $job->pid;
517 }
518
519 my $json_data = $job->TO_JSON();
520 $json_data->{stamp} = $spawn_time;
521 $run->jobs->write($json_data);
522
523 return $pid;
524 }
525
526 sub end_test_loop {
527 my $self = shift;
528
529 my $state = $self->state;
530
531 no warnings 'uninitialized';
532 if (!$self->{+STAGE} || $self->{+STAGE} eq 'default' || $self->{+STAGE} eq 'base') {
533 $self->{+RESPAWN_RUNNER_CALLBACK}->()
534 if $self->preloader->check($state) || ($self->{+SIGNAL} && $self->{+SIGNAL} eq 'HUP');
535 }
536
537 if ($self->preloader->check($state)) {
538 $self->{+SIGNAL} //= 'HUP';
539 return 1;
540 }
541
542 return 1 if $self->{+SIGNAL};
543
544 return 1 if $state->done;
545
546 return 0;
547 }
548
549 sub set_proc_exit {
550 my $self = shift;
551 my ($proc, $exit, $time, @args) = @_;
552
553 if ($proc->isa('Test2::Harness::Runner::Job')) {
554 my $task = $proc->task;
555
556 my $timed_out = 0;
557 if ( !$exit && ref $self->{run_reached_timeout} && $self->{run_reached_timeout}->{ $task->{job_id} } ) {
558 delete $self->{run_reached_timeout}->{ $task->{job_id} };
559 $timed_out = 1;
560 }
561
562 if (($exit || $timed_out) && $proc->is_try < ($proc->retry // 0) ) {
563 $self->state->retry_task($task->{job_id});
564 push @args => 'will-retry';
565 }
566 else {
567 $self->state->stop_task($task->{job_id});
568 }
569
570 if(my $bail = $exit ? $proc->bailed_out : 0) {
571 print "$$ $0 BAIL-OUT detected: $bail\n";
572 if ($self->settings->runner->abort_on_bail) {
573 print "$$ $0 Aborting the test run...\n";
574 $self->state->halt_run($task->{run_id});
575 }
576 }
577 }
578 elsif ($proc->isa('Test2::Harness::Runner::Preloader::Stage')) {
579 my $stage = $proc->name;
580
581 if ($exit != 0) {
582 my $e = parse_exit($exit);
583 my $err = "$$ $0 Child stage '$stage' did not exit cleanly (sig: $e->{sig}, err: $e->{err})!\n";
584 $self->{+MONITOR_PRELOADS} ? warn $err : die $err;
585 }
586
587 if ($self->{+MONITOR_PRELOADS} && $self->{+CAN_STAGE} && !$self->end_test_loop) {
588 my $pid = $$;
589 my ($name, @procs) = $self->preloader->_preload_stages($stage);
590 $self->watch($_) for @procs;
591 longjump "Stage-Runner" => $name unless $pid == $$;
592 }
593 }
594
595 if ($self->{+SCHEDULER_PID} && $proc->pid == $self->{+SCHEDULER_PID}) {
596 delete $self->{+SCHEDULER_PID};
597
598 if ($exit) {
599 my $e = parse_exit($exit);
600 print STDERR "\n$$ $0 Scheduler process (pid: @{[$proc->pid]}) exited unexpectedly (sig: $e->{sig}, err: $e->{err})!\n";
601 print STDERR "$$ $0 Aborting test run due to scheduler death.\n\n";
602 $self->{+SIGNAL} //= 'TERM';
603 }
604 elsif (!$self->{+SIGNAL} && !$self->state->done) {
605 print STDERR "\n$$ $0 Scheduler process (pid: @{[$proc->pid]}) exited prematurely (exit: 0) with pending work.\n\n";
606 $self->{+SIGNAL} //= 'TERM';
607 }
608 }
609
610 $self->SUPER::set_proc_exit($proc, $exit, $time, @args);
611 }
612
613 1;
614
615 __END__
616
617 =pod
618
619 =encoding UTF-8
620
621 =head1 NAME
622
623 Test2::Harness::Runner - Base class for test runners
624
625 =head1 DESCRIPTION
626
627 This module does the heavy lifting of running all the tests.
628
629 You should never need to create an instance of the runner yourself. In most
630 cases the runner module is exposed via a callback or a plugin affordance.
631
632 =head1 PUBLIC METHODS
633
634 =head2 FROM SETTINGS
635
636 These are attributes with values set from the L<Test2::Harness::Settings>
637 instance created from command line arguments.
638
639 See L<App::Yath::Options::Runner> for the most up to date documentation on
640 these.
641
642 =over 4
643
644 =item $runner->includes
645
646 =item $runner->tlib
647
648 =item $runner->lib
649
650 =item $runner->blib
651
652 =item $runner->unsafe_inc
653
654 =item $runner->use_fork
655
656 =item $runner->preloads
657
658 =item $runner->preload_threshold
659
660 =item $runner->switches
661
662 =item $runner->cover
663
664 =item $runner->event_timeout
665
666 =item $runner->post_exit_timeout
667
668 =back
669
670 =head2 FROM CONSTRUCTION
671
672 These attributes are set when the runner is created.
673
674 =over 4
675
676 =item $path = $runner->dir
677
678 Path to the working directory.
679
680 =item $settings = $runner->settings
681
682 The L<App::Yath::Settings> instance.
683
684 =item $coderef = $runner->fork_job_callback
685
686 Callback used to spawn new tests via fork.
687
688 =item $coderef = $runner->respawn_runner_callback
689
690 Callback to restart the runner process.
691
692 =item $bool = $runner->monitor_preloads
693
694 True if preloads should be watched for changes.
695
696 =item $int = $runner->jobs_todo
697
698 A count of total jobs to run. This will always be 0 in a persistent runner.
699
700 =back
701
702 =head2 OTHER PUBLIC METHODS
703
704 If a method is not documented here then it is an implementation detail and you
705 should not use it.
706
707 =over 4
708
709 =item $class = $runner->job_class
710
711 Class for new test jobs.
712
713 =item $preload = $runner->preloader
714
715 Get the L<Test2::Harness::Runner::Preloader> instance.
716
717 =item $state = $runner->state
718
719 Get the L<Test2::Harness::Runner::State> instance.
720
721 =item @list = $runner->all_libs
722
723 Get all the libs that should be added to @INC by default. Note that specific
724 runs and even specific tests can have custom paths on top of these.
725
726 =back
727
728 =head1 SOURCE
729
730 The source code repository for Test2-Harness can be found at
731 F<http://github.com/Test-More/Test2-Harness/>.
732
733 =head1 MAINTAINERS
734
735 =over 4
736
737 =item Chad Granum E<lt>[email protected]<gt>
738
739 =back
740
741 =head1 AUTHORS
742
743 =over 4
744
745 =item Chad Granum E<lt>[email protected]<gt>
746
747 =back
748
749 =head1 COPYRIGHT
750
751 Copyright 2020 Chad Granum E<lt>[email protected]<gt>.
752
753 This program is free software; you can redistribute it and/or
754 modify it under the same terms as Perl itself.
755
756 See F<http://dev.perl.org/licenses/>
757
758 =cut