lib/Myriad/Bootstrap.pm

filter: Statementstmt 47.9% 81 / 169 Branchbran 30.3% 17 / 56 Conditioncond 28.5% 2 / 7 MC/DCmcdc 0.0% 0 / 4 Subroutinesub 43.7% 7 / 16 Podpod 60.0% 3 / 5 totaltotal 42.8% 110 / 257 CC 37 SCAR 44.3
CC
37
Cov
43%
boot
163.9
check_messages_in_pipe
30.0
__ANON__
12.0
CRAP 83.8
↑ Summary lib/Myriad/UI/Readline.pm »
1 package Myriad::Bootstrap;
2  
3 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 3 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 3 our $VERSION = '1.001'; # VERSION
9 3 our $AUTHORITY = 'cpan:DERIV'; # AUTHORITY
10  
11 =encoding utf8
12  
13 =head1 NAME
14  
15 Myriad::Bootstrap - dæmon functionality and hot-reload for Myriad
16  
17 =head1 DESCRIPTION
18  
19 Controller process for managing an application.
20  
21 Provides a minimal parent process which starts up a child process for
22 running the real application code. A pipe is maintained between parent
23 and child for exchanging status information, with a secondary UNIX domain
24 socket for filedescriptor handover.
25  
26 The parent process loads only two additional modules - strict and warnings
27 - with the rest of the app-specific modules being loaded in the child. This
28 is enforced: any other modules found in C<< %INC >> will cause the process to
29 exit immediately.
30  
31 Signals:
32  
33 =over 4
34  
35 =item * C<HUP> - Request to recycle all child processes
36  
37 =item * C<TERM> - Shut down all child processes gracefully
38  
39 =item * C<KILL> - Immediate shutdown for all child processes
40  
41 =back
42  
43 The purpose of this class is to support development usage: it provides a
44 minimal base set of code that can load up the real modules in separate
45 forks, and tear them down again when dependencies or local files change.
46  
47 We avoid even the standard CPAN modules because one of the changes we're
48 watching for is C<< cpanfile >> content changing, if there's a new module
49 or updated version we want to be very sure that it's properly loaded.
50  
51 One thing we explicitly B<don't> try to do is handle Perl version or executable
52 changing from underneath us - so this is very much a fork-and-call approach,
53 rather than fork-and-exec.
54  
55 =cut
56  
57 our %ALLOWED_MODULES = map {
58 3 $_ => 1
59 } qw(
60 strict
61 warnings
62 ),
63 __PACKAGE__;
64  
65 3 our %constant;
66  
67 # See perldoc perlport for the difference between this and \r\n
68 3 my $CRLF = "\x0D\x0A";
69  
70 =head1 METHODS - Class
71  
72 =head2 allow_modules
73  
74 Add modules to the whitelist.
75  
76 Takes a list of module names in the same format as C<< %INC >> keys.
77  
78 Don't ever use this.
79  
80 =cut
81  
82 0 ▶sub allow_modules {
Subroutine allow_modules: not called CC=1 SCAR=6.9
Pod documented
83 0 my $class = shift;
84 0 @ALLOWED_MODULES{@_} = (1) x @_;
85 }
86  
87  
88 =head2 open_pipe
89  
90 use socketpair to establish communication between parent/child later.
91  
92 =cut
93  
94 2 ▶sub open_pipe {
Subroutine open_pipe: called CC=2 SCAR=6.9
Pod documented
95 # Establish comms channel for child process
96 socketpair my $child_pipe, my $parent_pipe, $constant{AF_UNIX}, $constant{SOCK_STREAM}, $constant{PF_UNSPEC}
97 2 ▶ or die $!;
Branch: 1 branch
BranchTrueFalseTotal
socketpair my $child_pipe, my $parent_pipe, $Myriad::Bootstrap::constant{"AF_UNIX"}, $Myriad::Bootstrap::constant{"SOCK_STREAM"}, $Myriad::Bootstrap::constant{"PF_UNSPEC"} or die $! 2 0 2
98  
99 { # Unbuffered writes
100 2 my $old = select($child_pipe);
101 2 $| = 1; select($parent_pipe);
102 2 $| = 1; select($old);
103 }
104  
105 2 make_pipe_nonblocking($parent_pipe);
106 2 make_pipe_nonblocking($child_pipe);
107  
108 2 return ($parent_pipe, $child_pipe);
109 }
110  
111  
112 =head2 make_pipe_noneblocking
113  
114 Takes a pipe and makes it nonblocking by applying C<O_NONBLOCK>
115  
116 =cut
117  
118 4 ▶sub make_pipe_nonblocking {
Subroutine make_pipe_nonblocking: called CC=3 SCAR=11.7
Pod undocumented
119 4 my $pipe = shift;
120 4 ▶ my $flags = fcntl($pipe, $constant{F_GETFL}, 0)
Branch: 1 branch
BranchTrueFalseTotal
my $flags = fcntl($pipe, $Myriad::Bootstrap::constant{"F_GETFL"}, 0) or die "Can't get flags for the socket: $!\n" 4 0 4
121 or die "Can't get flags for the socket: $!\n";
122  
123 $flags = fcntl($pipe, $constant{F_SETFL}, $flags | $constant{O_NONBLOCK})
124 4 ▶ or die "Can't set flags for the socket: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
$flags = fcntl($pipe, $Myriad::Bootstrap::constant{"F_SETFL"}, $flags | $Myriad::Bootstrap::constant{"O_NONBLOCK"}) or die "Can't set flags for the socket: $!\n" 4 0 4
125 }
126  
127 0 ▶sub check_messages_in_pipe {
Subroutine check_messages_in_pipe: not called CC=5 SCAR=34.0
Pod undocumented
128 0 my ($pipe, $on_read) = @_;
129 # See https://perldoc.perl.org/functions/select#select-RBITS,WBITS,EBITS,TIMEOUT
130 # for a better understanding
131 0 my $input = '';
132 0 my $rin = my $win = '';
133 0 vec($rin, fileno($pipe), 1) = 1;
134 0 my $ein = $rin | $win;
135  
136 0 ▶ die $! unless (my $nfound = select my $rout = $rin, my $wout = $win, my $eout = $ein, 0.5) > -1;
Branch: 1 branch
BranchTrueFalseTotal
unless (my $nfound = select(my $rout = $rin, my $wout = $win, my $eout = $ein, "0.5")) > -1 0 0 0
137  
138 0 ▶ if($nfound) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nfound) 0 0 0
139 0 my $rslt = sysread $pipe, my $buf, 4096;
140 0 ▶ return 0 unless $rslt;
Branch: 1 branch
BranchTrueFalseTotal
unless $rslt 0 0 0
141 0 $input .= $buf;
142 0 ▶ while($input =~ s/^[\x0D\x0A]*(.*)(?:\x0D\x0A)+//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($input =~ s/^[\x0D\x0A]*(.*)(?:\x0D\x0A)+//) 0 0 0
143 0 $on_read->($1);
144 }
145 }
146  
147 0 return 1;
148 }
149  
150 =head2 boot
151  
152 Given a target coderef or classname, prepares the fork and communication
153 pipe, then starts the code.
154  
155 =cut
156  
157 2 ▶sub boot {
Subroutine boot: called CC=25 SCAR=51.0
Pod documented
158 2 my ($class, $target) = @_;
159 2 my $parent_pid = $$;
160 2 my @children_pids;
161  
162 { # Read constants from various modules without loading them into the main process
163 2 ▶ die $! unless defined(my $pid = open my $child, '-|');
Branch: 1 branch
BranchTrueFalseTotal
unless defined(my $pid = open(my $child, "-|")) 0 2 2
164 2 my %constant_map = (
165 Socket => [qw(AF_UNIX SOCK_STREAM PF_UNSPEC)],
166 Fcntl => [qw(F_GETFL F_SETFL O_NONBLOCK)],
167 POSIX => [qw(WNOHANG)],
168 );
169 2 ▶ unless($pid) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($pid) 1 1 2
170 # We've forked, so we're free to load any extra modules we'd like here
171 1 require Module::Load;
172 1 for my $pkg (sort keys %constant_map) {
173 3 Module::Load::load($pkg);
174 3 $pkg->import;
175 {
176 3 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
177 3 print "$_=" . *{join '::', $pkg, $_}->() . "\n" for @{$constant_map{$pkg}};
178 }
179 }
180 1 exit 0;
181 }
182 {
183 # A poor attempt at a data-exchange protocol indeed, but one with the advantage
184 # of simplicity and readability for anyone investigating via `strace`
185 1 my @constants = map @$_, values %constant_map;
186 1 ▶ while(<$child>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline $child)) 7 1 8
187 7 my ($k, $v) = /^([^=]+)=(.*)$/;
188 7 $constant{$k} = $v;
189 }
190 1 ▶ close $child or die $!;
Branch: 1 branch
BranchTrueFalseTotal
close $child or die $! 1 0 1
191 1 die "Missing constant $_" for grep !exists $constant{$_}, @constants;
192 }
193 }
194  
195 1 my ($inotify_parent_pipe, $inotify_child_pipe) = open_pipe();
196  
197 {
198 1 ▶ if (my $pid = fork // die "fork! $!") {
Branch: 1 branch
BranchTrueFalseTotal
if (my $pid = fork // die("fork! $!")) { } 1 0 1
Condition50%1/2
fork // die("fork! $!")
l!l
10
MC/DC0%0/1
fork // die("fork! $!")
fork
Truth table50%1/2
A
A= fork
Aresult
11
00
199 1 push @children_pids, $pid;
200 1 close $inotify_parent_pipe;
201 } else {
202  
203 0 close $inotify_child_pipe;
204  
205 0 ▶ local $SIG{HUP}= sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
206 0 say "$pid - inotify process terminated";
207 0 exit 0;
208 0 };
209  
210 0 require Linux::Inotify2;
211  
212 0 my $watch_mask = Linux::Inotify2->IN_CLOSE_WRITE;
213  
214 0 my $watcher = Linux::Inotify2->new();
215 0 $watcher->blocking(0);
216  
217 0 my $on_change;
218 0 ▶ $on_change = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
219 # Some editors like vim will set this flag to true
220 # Linux::Inotify2 will cancel the watcher if it gets
221 # this flag https://stackoverflow.com/a/16762193
222 0 my $e = shift;
223 0 ▶ if($e->IN_IGNORED) {
Branch: 1 branch
BranchTrueFalseTotal
if ($e->IN_IGNORED) 0 0 0
224 0 $watcher->watch($e->fullname, $watch_mask, $on_change);
225 }
226 0 print $inotify_parent_pipe "change$CRLF";
227  
228 0 };
229  
230 0 while (1) {
231 0 ▶ check_messages_in_pipe($inotify_parent_pipe, sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
232 0 my $module_path = shift;
233 0 say "$$ - Going to watch $module_path for changes";
234 0 $watcher->watch($module_path, $watch_mask, $on_change);
235 0 });
236  
237 0 $watcher->poll;
238 }
239 0 exit 0;
240 }
241 }
242  
243 1 my $active = 1;
244 1 my $watched_modules = {};
245  
246 # Make sure filewatcher is alive before forking
247 1 my $attempts = 3;
248 1 ▶ while ($attempts > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($attempts > 0) 3 1 4
249 3 ▶ if(waitpid $children_pids[0], $constant{WNOHANG}) {
Branch: 1 branch
BranchTrueFalseTotal
if (waitpid $children_pids[0], $Myriad::Bootstrap::constant{'WNOHANG'}) { } 0 3 3
250 0 say "$$ - filewatcher process isn't running";
251 0 $active = 0;
252 0 $attempts = 0;
253 } else {
254 3 sleep 1;
255 3 $attempts--;
256 }
257 }
258  
259 1 ▶ say "$$ - filewatcher look stable" if $active;
Branch: 1 branch
BranchTrueFalseTotal
if $active 1 0 1
260  
261 MAIN:
262 1 ▶ while($active) {
Branch: 1 branch
BranchTrueFalseTotal
if ($active) 1 0 1
263 1 my ($parent_pipe, $child_pipe) = open_pipe();
264  
265 1 ▶ if(my $pid = fork // die "fork: $!") {
Branch: 1 branch
BranchTrueFalseTotal
if (my $pid = fork // die("fork: $!")) { } 1 0 1
Condition50%1/2
fork // die("fork: $!")
l!l
10
MC/DC0%0/1
fork // die("fork: $!")
fork
Truth table50%1/2
A
A= fork
Aresult
11
00
266 1 close $parent_pipe;
267 1 say "$$ - Parent with $pid child";
268 1 push @children_pids, $pid;
269  
270 # Note that we don't have object methods available yet, since that'd pull in IO::Handle
271  
272 { # Make sure we didn't pull in anything unexpected
273 1 my %found = map {
274 # Convert filename to package name
275 1 (s{/}{::}gr =~ s{\.pm$}{}r) => 1,
276 } keys %INC;
277  
278 # Trim out anything that we arbitrarily decided would be fine
279 1 delete @found{keys %ALLOWED_MODULES};
280  
281 1 my $loaded_modules = join ',', sort keys %found;
282 1 ▶ if ($loaded_modules) {
Branch: 1 branch
BranchTrueFalseTotal
if ($loaded_modules) 1 0 1
283 1 kill QUIT => $_ for @children_pids;
284 1 die "excessive module loading detected: $loaded_modules";
285 }
286 }
287  
288 0 ▶ local $SIG{HUP} = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
289 0 say "$$ - HUP detected in parent";
290 0 kill QUIT => $pid;
291 0 };
292  
293 # To avoide terminating the program
294 # with bad exit code when the file watcher is terminated
295 0 local $SIG{PIPE} = 'IGNORE';
296  
297 0 print $child_pipe "Parent active$CRLF";
298 0 my $active = 1;
299 ACTIVE:
300 0 ▶ while ($active) {
Branch: 1 branch
BranchTrueFalseTotal
if ($active) 0 0 0
301 0 ▶ $active = 0 unless check_messages_in_pipe($inotify_child_pipe, sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
302 0 say "$$ - File change has been detected, reloading..";
303 0 kill QUIT => $pid;
304 # wait for the process to finish
305 0 waitpid $pid, 0;
306 0 next MAIN;
307 0 ▶ });
Branch: 1 branch
BranchTrueFalseTotal
unless check_messages_in_pipe($inotify_child_pipe, sub { say "${$} - File change has been detected, reloading.."; kill "QUIT", $pid; waitpid $pid, 0; next MAIN; } ) 0 0 0
308  
309 0 ▶ $active = 0 unless check_messages_in_pipe($child_pipe, sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
310 0 my $module = shift;
311 0 ▶ if (!$watched_modules->{$module}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $watched_modules->{$module}) 0 0 0
312 0 ▶ if(print $inotify_child_pipe "${module}${CRLF}") {
Branch: 1 branch
BranchTrueFalseTotal
if (print $inotify_child_pipe "$module$CRLF") { } 0 0 0
313 0 $watched_modules->{$module} = 1;
314 } else {
315 0 $active = 0;
316 0 say "$$ - Broken pipe to the file watcher";
317 }
318 }
319 0 ▶ });
Branch: 1 branch
BranchTrueFalseTotal
unless check_messages_in_pipe($child_pipe, sub { my $module = shift(); if (not $watched_modules->{$module}) { if (print $inotify_child_pipe "$module$CRLF") { $watched_modules->{$module} = 1; } else { $active = 0; say "${$} - Broken pipe to the file watcher"; } ; } ; } ) 0 0 0
320  
321 0 ▶ if(my $exit = waitpid -1, $constant{WNOHANG}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $exit = waitpid(-1, $Myriad::Bootstrap::constant{"WNOHANG"})) 0 0 0
322 0 say "$$ Exit was $exit";
323 # stop the other processes
324 0 kill QUIT => $_ for grep {$_ ne $exit} @children_pids;
325 0 last MAIN;
326 }
327 }
328 0 say "$$ - Done";
329 0 exit 0;
330 } else {
331 0 say "$$ - Child with parent " . $parent_pid;
332 0 close $child_pipe;
333 0 close $inotify_child_pipe;
334 # We'd expect to pass through some more details here as well
335 0 my %args = (
336 parent_pipe => $parent_pipe
337 );
338  
339 0 ▶ unshift @INC, sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
340 0 my ($code, $module) = @_;
341 0 ▶ my ($path) = grep { !ref and -r "$_/$module"} @INC;
Condition0%0/3
!ref($_) && -r "$_/$module"
!ll&&!rl&&r
000
MC/DC0%0/2
!ref($_) && -r "$_/$module"
!ref($_) -r "$_/$module"
Truth table0%0/3
not(A) && B
A= !ref($_)B= -r "$_/$module"
ABresult
0X0
100
111
342 0 ▶ if ($path) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path) 0 0 0
343 0 print $parent_pipe "$path/${module}${CRLF}";
344 }
345 0 };
346  
347 eval {
348 # Support coderef or package name
349 0 ▶ if(ref $target) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $target) { } 0 0 0
350 0 $target->(%args);
351 } else {
352 0 require Module::Load;
353 0 Module::Load::load($target);
354 0 my $module = $target->new;
355 0 $module->configure_from_argv(@ARGV)->await;
356 0 $module->run()->await;
357 }
358 0 1;
359 0 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { if (ref $target) { &$target(%args); } else { require Module::Load; Module::Load::load($target); my $module = $target->new; $module->configure_from_argv(@ARGV)->await; $module->run->await; } ; 1 } } or do { my $error = $@; $error =~ s/\n/\n\t/g; print "${$} - target code/module exited unexpectedly due:\n\t$error" } 0 0 0
360 0 my $error = $@;
361 0 $error =~ s/\n/\n\t/g;
362 0 print "$$ - target code/module exited unexpectedly due:\n\t$error";
363 };
364  
365 0 exit 0;
366 }
367 }
368 }
369  
370 3 1;
371  
372 __END__
↑ Summary lib/Myriad/UI/Readline.pm »