Debian Codegraph @

lib/Test2/Harness/Runner/Preloader.pm

raw
1 package Test2::Harness::Runner::Preloader;
2 use strict;
3 use warnings;
4
5 our $VERSION = '1.000179';
6
7 use B();
8 use Carp qw/confess croak/;
9 use Fcntl qw/LOCK_EX LOCK_UN/;
10 use Time::HiRes qw/time sleep/;
11 use Test2::Harness::Util qw/open_file file2mod mod2file lock_file unlock_file clean_path/;
12 use Test2::Harness::Util::IPC qw/USE_P_GROUPS/;
13
14 use Test2::Harness::Runner::Reloader;
15 use Test2::Harness::Runner::Preloader::Stage;
16
17 use File::Spec();
18 use List::Util qw/pairgrep/;
19
20 use Test2::Harness::Util::HashBase(
21 qw{
22 <dir
23 <preloads
24 <done
25 <below_threshold
26
27 <dtrace <reloader
28
29 <staged <started_stages <stage
30
31 <dump_depmap
32 <changed
33 <restrict_reload
34
35 <blacklist_file
36 <blacklist_lock
37 <blacklist
38
39 <monitored
40 <last_update
41 },
42
43 '<monitor', # This means watch for changes, restart stage if any found
44 '<reload', # Try to reload in place instead of restart stage
45 );
46
47 sub init {
48 my $self = shift;
49
50 $self->{+PRELOADS} //= [];
51
52 $self->{+BELOW_THRESHOLD} //= 0;
53
54 return if $self->{+BELOW_THRESHOLD};
55
56 $self->{+MONITOR} = 1 if $self->{+RELOAD};
57
58 my $need_depmap = $self->{+RELOAD} || $self->{+MONITOR} || $self->{+DUMP_DEPMAP};
59
60 if ($need_depmap) {
61 require Test2::Harness::Runner::DepTracer;
62 $self->{+DTRACE} //= Test2::Harness::Runner::DepTracer->new();
63 }
64
65 if ($self->{+MONITOR} || $self->{+RELOAD}) {
66 $self->{+BLACKLIST} //= {};
67 $self->{+BLACKLIST_FILE} //= File::Spec->catfile($self->{+DIR}, 'BLACKLIST');
68 }
69
70 $self->{+RELOADER} = Test2::Harness::Runner::Reloader->new(
71 stat_min_gap => 2,
72 notify_cb => sub { $self->_reload_cb_notify(@_) },
73 find_loaded_cb => sub { $self->_reload_cb_find_loaded(@_) },
74 should_watch_cb => sub { $self->_reload_cb_should_watch(@_) },
75 can_reload_cb => sub { $self->_reload_cb_can_reload(@_) },
76 reload_cb => sub { $self->_reload_cb_reload(@_) },
77 delete_symbol_cb => sub { $self->_reload_cb_delete_symbol(@_) },
78 );
79 }
80
81 sub stage_check {
82 my $self = shift;
83 my ($stage) = @_;
84
85 return 0 if $self->{+BELOW_THRESHOLD};
86
87 my $p = $self->{+STAGED} or return 0;
88 return 1 if $stage eq 'NOPRELOAD';
89 return 1 if $p->stage_lookup->{$stage};
90 return 0;
91 }
92
93 sub task_stage {
94 my $self = shift;
95 my ($file, $wants) = @_;
96
97 $wants //= "";
98
99 return 'default' if $self->{+BELOW_THRESHOLD};
100 return 'default' unless $self->{+STAGED};
101
102 return $wants if $wants && $self->stage_check($wants);
103
104 my $stage = $self->{+STAGED}->file_stage($file) // $self->{+STAGED}->default_stage;
105
106 return $stage;
107 }
108
109 sub preload {
110 my $self = shift;
111
112 croak "Already preloaded" if $self->{+DONE};
113
114 return 'default' if $self->{+BELOW_THRESHOLD};
115
116 my $preloads = $self->{+PRELOADS} or return 'default';
117 return 'default' unless @$preloads;
118
119 require Test2::API;
120 Test2::API::test2_start_preload();
121
122 # Not loading blacklist yet because any preloads in this list need to
123 # happen regardless of the blacklist.
124 if ($self->{+MONITOR} || $self->{+DTRACE}) {
125 $self->_monitor_preload($preloads);
126 }
127 else {
128 $self->_preload($preloads);
129 }
130
131 $self->{+DONE} = 1;
132 }
133
134 sub preload_stages {
135 my $self = shift;
136 return 'default' unless $self->{+STAGED};
137 return $self->_preload_stages('NOPRELOAD', @{$self->{+STAGED}->stage_list});
138 }
139
140 sub _preload_stages {
141 my $self = shift;
142 my @stages = @_;
143
144 my $name = 'base';
145 my @procs;
146
147 while (my $stage = shift @stages) {
148 $stage = $self->{+STAGED}->stage_lookup->{$stage} unless ref $stage || $stage eq 'NOPRELOAD';
149
150 my $proc = $self->launch_stage($stage);
151
152 if ($proc) {
153 push @procs => $proc;
154 next;
155 }
156
157 # We are in the stage now, reset these
158 if (ref $stage) {
159 $name = $stage->name;
160 @procs = ();
161 @stages = @{$stage->children};
162 }
163 else { # NOPRELOAD
164 $name = $stage;
165 @procs = ();
166 @stages = ();
167 }
168
169 $self->start_stage($stage);
170 }
171
172 return($name, @procs);
173 }
174
175 sub launch_stage {
176 my $self = shift;
177 my ($stage) = @_;
178
179 $stage = $self->{+STAGED}->stage_lookup->{$stage} unless ref $stage || $stage eq 'NOPRELOAD';
180
181 my $name = ref($stage) ? $stage->name : $stage;
182
183 my $pid = fork // die "Could not fork: $!";
184
185 return Test2::Harness::Runner::Preloader::Stage->new(
186 pid => $pid,
187 name => $name,
188 ) if $pid;
189
190 setpgrp(0, 0) if USE_P_GROUPS;
191 $0 .= "-$name";
192 $ENV{T2_HARNESS_STAGE} = $name;
193
194 return;
195 }
196
197 sub start_stage {
198 my $self = shift;
199 my ($stage) = @_;
200
201 if ($self->{+STAGED}) {
202 if ($stage && !ref($stage)) {
203 $stage = $self->{+STAGED}->stage_lookup->{$stage};
204 }
205 }
206 else {
207 $stage = undef;
208 }
209
210 $self->{+STAGE} = $stage;
211
212 $self->load_blacklist if $self->{+MONITOR};
213
214 # Localize these in case something we preload tries to modify them.
215 local $SIG{INT} = $SIG{INT};
216 local $SIG{HUP} = $SIG{HUP};
217 local $SIG{TERM} = $SIG{TERM};
218
219 my $preloads = $stage ? $stage->load_sequence : [];
220
221 my $meth = $self->{+MONITOR} || $self->{+DTRACE} ? '_monitor_preload' : '_preload';
222
223 $self->$meth($preloads, $stage->watches) if $preloads && @$preloads;
224
225 $self->_monitor() if $self->{+MONITOR};
226 }
227
228 sub get_stage_callback {
229 my $self = shift;
230 my ($name) = @_;
231
232 my $stage = $self->{+STAGE} or return undef;
233 return undef unless ref $stage;
234 return $stage->$name;
235 }
236
237 sub _monitor_preload {
238 my $self = shift;
239 my ($preloads, $watch) = @_;
240
241 my $block = {%{$self->blacklist}};
242 my $dtrace = $self->dtrace;
243
244 $dtrace->start;
245 $self->_preload($preloads, $block, $dtrace->my_require);
246 $dtrace->add_callbacks(%$watch) if $watch;
247 $dtrace->stop;
248
249 return;
250 }
251
252 sub _preload {
253 my $self = shift;
254 my ($preloads, $block, $require_sub) = @_;
255
256 $block //= {};
257
258 my %seen;
259 for my $mod (@$preloads) {
260 next if $seen{$mod}++;
261
262 if (ref($mod) eq 'CODE') {
263 next if eval { $mod->($block, $require_sub); 1 };
264 $self->{+MONITOR} ? warn $@ : die $@;
265 next;
266 }
267
268 next if $block && $block->{$mod};
269
270 next if eval { $self->_preload_module($mod, $block, $require_sub); 1 };
271 $self->{+MONITOR} ? warn $@ : die $@;
272 }
273
274 return;
275 }
276
277 sub _preload_module {
278 my $self = shift;
279 my ($mod, $block, $require_sub) = @_;
280
281 my $file = mod2file($mod);
282
283 $require_sub ? $require_sub->($file) : require $file;
284
285 return unless $mod->can('TEST2_HARNESS_PRELOAD');
286
287 die "You cannot load a Test2::Harness::Runner::Preload module from within another" if $self->{+DONE};
288
289 $self->{+STAGED} //= do {
290 require Test2::Harness::Runner::Preload;
291 Test2::Harness::Runner::Preload->new();
292 };
293
294 $self->{+STAGED}->merge($mod->TEST2_HARNESS_PRELOAD);
295
296 return;
297 }
298
299 sub eager_stages {
300 my $self = shift;
301
302 return unless $self->{+STAGED};
303 return $self->{+STAGED}->eager_stages;
304 }
305
306 sub load_blacklist {
307 my $self = shift;
308
309 my $bfile = $self->{+BLACKLIST_FILE};
310 my $blacklist = $self->{+BLACKLIST};
311
312 return unless -f $bfile;
313
314 my $fh = open_file($bfile, '<');
315 while(my $pkg = <$fh>) {
316 chomp($pkg);
317 $blacklist->{$pkg} = 1;
318 }
319 }
320
321 sub _lock_blacklist {
322 my $self = shift;
323
324 return $self->{+BLACKLIST_LOCK} if $self->{+BLACKLIST_LOCK};
325
326 my $bl = lock_file($self->{+BLACKLIST_FILE}, '>>');
327 seek($bl,2,0);
328
329 return $self->{+BLACKLIST_LOCK} = $bl;
330 }
331
332 sub _unlock_blacklist {
333 my $self = shift;
334
335 my $bl = delete $self->{+BLACKLIST_LOCK} or return;
336
337 $bl->flush;
338 unlock_file($bl);
339 close($bl);
340
341 return;
342 }
343
344 sub _notify {
345 my $self = shift;
346 for my $msg (@_) {
347 print "$$ $0 - $msg\n";
348 }
349 }
350
351 sub _reload_cb_notify {
352 my $self = shift;
353 my ($type, $info) = @_;
354
355 return $self->_notify("Runner detected a change in one or more preloaded modules...")
356 if $type eq 'changes_detected';
357
358 return $self->_notify("Runner detected changes in file '$info'...")
359 if $type eq 'file_changed';
360
361 return $self->_notify("Runner attempting to reload '$info->{file}' in place...")
362 if $type eq 'reload_inplace';
363
364 return $self->_notify(
365 "Runner failed to reload '$info->{file}' in place...",
366 map { split /\n/, $_ } grep { $_ } @{$info->{warnings} // []}, $info->{error},
367 ) if $type eq 'reload_fail';
368
369 require Data::Dumper;
370 local $Data::Dumper::Sortkeys = 1;
371 local $Data::Dumper::Maxdepth = 2;
372 return $self->_notify("Runner notification $type: " . (ref($info) ? Data::Dumper::Dumper($info) : $info) . "...");
373 }
374
375 sub _reload_cb_find_loaded { keys %{$_[0]->dtrace->loaded} }
376
377 sub _reload_cb_should_watch {
378 my $self = shift;
379 my ($reloader, $rel, $abs) = @_;
380
381 my $dirs = $self->{+RESTRICT_RELOAD};
382 return 1 unless $dirs && @$dirs;
383
384 for my $dir (@$dirs) {
385 return 1 if 0 == index($abs, $dir);
386 }
387
388 return 0;
389 }
390
391 sub _reload_cb_can_reload {
392 my $self = shift;
393 my %params = @_;
394
395 my $mod = $params{module};
396 my $file = $params{file};
397
398 return (0, reason => 'File is a yath preload module') if $mod->can('TEST2_HARNESS_PRELOAD');
399
400 if (my $cb = $self->get_stage_callback('reload_inplace_check')) {
401 my ($res, %fields) = $cb->(module => $mod, file => $file);
402 return ($res, %fields) if defined $res;
403 }
404
405 return (1) unless $mod->can('import');
406
407 return (0, reason => 'File is an importer') if $mod->can('IMPORTER_MENU');
408
409 {
410 no strict 'refs';
411 return (0, reason => 'File is an importer') if @{"$mod\::EXPORT"};
412 return (0, reason => 'File is an importer') if @{"$mod\::EXPORT_OK"};
413 }
414
415 return (1);
416 }
417
418 sub find_churn {
419 my $self = shift;
420 my ($file) = @_;
421
422 # When a file is saved to disk it seems it can vanish temporarily. Use this loop to wait for it...
423 my ($fh, $ok, $error);
424 for (1 .. 50) {
425 local $@;
426 $ok = eval { $fh = open_file($file) };
427 $error = "LOOP $_: $@";
428 last if $ok;
429 sleep 0.02;
430 }
431
432 die $error // "Unknown error opening file '$file'" unless $fh;
433
434 my $active = 0;
435 my @out;
436
437 my $line_no = 0;
438 while (my $line = <$fh>) {
439 $line_no++;
440
441 if ($active) {
442 if ($line =~ m/^\s*#\s*HARNESS-CHURN-STOP\s*$/) {
443 push @{$out[-1]} => $line_no;
444 $active = 0;
445 next;
446 }
447 else {
448 $out[-1][-1] .= $line;
449 next;
450 }
451 }
452
453 if ($line =~ m/^\s*#\s*HARNESS-CHURN-START\s*$/) {
454 $active = 1;
455 push @out => [$line_no, ''];
456 }
457 }
458
459 return @out;
460 }
461
462 sub _reload_cb_reload {
463 my $self = shift;
464 my %params = @_;
465
466 my ($file, $rel, $mod) = @params{qw/file relative module/};
467
468 my $callbacks;
469 if (my $dtrace = $self->dtrace) {
470 $callbacks = $dtrace->callbacks;
471 }
472 $callbacks //= {};
473
474 if (my $cb = $callbacks->{$file} // $callbacks->{$rel}) {
475 $self->_notify("Changed file '$rel' has a reload callback, executing it instead of regular reloading...");
476 my $ret = $cb->();
477 return (1, callback_return => $ret);
478 }
479
480 if (my @churn = $self->find_churn($file)) {
481 $self->_notify("Changed file '$rel' contains churn sections, running them instead of a full reload...");
482
483 for my $churn (@churn) {
484 my ($start, $code, $end) = @$churn;
485 my $sline = $start + 1;
486 if (eval "package $mod;\nuse strict;\nuse warnings;\nno warnings 'redefine';\n#line $sline $file\n$code\n ;1;") {
487 $self->_notify("Success reloading churn block ($file lines $start -> $end)");
488 }
489 else {
490 $self->_notify("Error reloading churn block ($file lines $start -> $end): $@");
491 }
492 }
493
494 return (1);
495 }
496
497 return (0, reason => 'reloading disabled') unless $self->{+RELOAD};
498
499 return undef;
500 }
501
502 sub _reload_cb_delete_symbol {
503 my $self = shift;
504 my %params = @_;
505
506 my $sym = $params{symbol};
507 my $mod = $params{module};
508 my $file = $params{file};
509
510 # Make sure the changed file and the file that defined the sub are the same.
511 my $cb = $self->get_stage_callback('reload_remove_check') or return 0;
512 my $sub = $mod->can($sym) or return 0;
513 my $cobj = B::svref_2object($sub) or return 0;
514 my $subfile = $cobj->FILE or return 0;
515
516 my $res = $cb->(
517 mod => $mod,
518 sym => $sym,
519 sub => $sub,
520 from_file => -f $subfile ? clean_path($subfile) : $subfile,
521 reload_file => -f $file ? clean_path($file) : $file,
522 );
523
524 # 0 means do not skip, so if the cb returned true we do not skip
525 return 0 if $res;
526 return 1;
527 }
528
529 sub _monitor {
530 my $self = shift;
531
532 if ($self->{+MONITORED} && $self->{+MONITORED}->[0] == $$) {
533 die "Monitor already starated\n" . "\n=======\n$0\n" . Carp::longmess() . "\n=====\n" . $self->{+MONITORED}->[1] . "\n" . $self->{+MONITORED}->[2] . "\n=======\n";
534 }
535
536 $self->{+MONITORED} = [$$, $0, Carp::longmess()];
537
538 my $reloader = $self->{+RELOADER};
539 $reloader->reset();
540 $reloader->refresh();
541
542 return $self->{+MONITORED};
543 }
544
545 sub check {
546 my $self = shift;
547 my ($state) = @_;
548
549 return 1 if $self->{+CHANGED};
550
551 return 0 unless $self->{+MONITOR};
552
553 # Do not check for changes more often than 1 second (This is used in a loop that needs to be more often than once a second)
554 return 0 if $self->{+LAST_UPDATE} && 1 > (time - $self->{+LAST_UPDATE});
555 $self->{+LAST_UPDATE} = time;
556
557 my $dtrace = $self->dtrace;
558 $dtrace->start if $self->{+RELOAD};
559
560 my $results = $self->{+RELOADER}->reload_changes();
561
562 $dtrace->stop if $self->{+RELOAD};
563
564 my (@todo, @fails);
565 for my $item (values %$results) {
566 my $stage = $self->{+STAGE} ? $self->{+STAGE}->name : 'default';
567 $state->reload($stage => $item);
568 my $rel = $item->{reloaded};
569
570 next if $rel; # Reload success
571
572 if (defined $rel) { # Not reloaded, but no error
573 push @todo => $item;
574 next;
575 }
576 }
577
578 unless (@todo) {
579 $self->{+RELOADER}->refresh();
580 return 0;
581 }
582
583 $self->{+CHANGED} = 1;
584 $self->_notify("blacklisting changed files and reloading stage...");
585
586 my $bl = $self->_lock_blacklist();
587
588 my $dep_map = $self->dtrace->dep_map;
589
590 my %CNI = reverse pairgrep { $b } %INC;
591
592 my %seen;
593 while (@todo) {
594 my $item = shift @todo;
595 my $ref = ref($item);
596
597 my ($mod, $abs, $rel);
598 if ($ref eq 'HASH') {
599 ($mod, $abs, $rel) = @{$item}{qw/module file relative/};
600 }
601 elsif ($ref eq 'ARRAY') {
602 ($mod, $abs) = @$item;
603 $rel = $CNI{$abs} || $abs;
604 }
605 else {
606 die "Invalid ref type: $ref";
607 }
608
609 next if $seen{$abs}++;
610 next if $mod->can('TEST2_HARNESS_PRELOAD');
611 $self->_notify("Blacklisting $mod...");
612 print $bl "$mod\n";
613 my $next = $dep_map->{$abs} or next;
614 push @todo => @$next;
615 }
616
617 $self->_unlock_blacklist();
618
619 return 1;
620 }
621
622 1;
623
624 __END__
625
626 =pod
627
628 =encoding UTF-8
629
630 =head1 NAME
631
632 Test2::Harness::Runner::Preloader - Preload logic.
633
634 =head1 DESCRIPTION
635
636 This module is responsible for preloading libraries before running tests. This
637 entire module is considered an "Implementation Detail". Please do not rely on
638 it always staying the same, or even existing in the future. Do not use this
639 directly.
640
641 =head1 SOURCE
642
643 The source code repository for Test2-Harness can be found at
644 F<http://github.com/Test-More/Test2-Harness/>.
645
646 =head1 MAINTAINERS
647
648 =over 4
649
650 =item Chad Granum E<lt>[email protected]<gt>
651
652 =back
653
654 =head1 AUTHORS
655
656 =over 4
657
658 =item Chad Granum E<lt>[email protected]<gt>
659
660 =back
661
662 =head1 COPYRIGHT
663
664 Copyright 2020 Chad Granum E<lt>[email protected]<gt>.
665
666 This program is free software; you can redistribute it and/or
667 modify it under the same terms as Perl itself.
668
669 See F<http://dev.perl.org/licenses/>
670
671 =cut
672