File Coverage

lib/RPC/Switch/Client/Tiny/Async.pm
Criterion Covered Total %
statement 111 131 84.7
branch 37 54 68.5
condition 5 15 33.3
subroutine 16 17 94.1
pod 0 11 0.0
total 169 228 74.1


line stmt bran cond sub pod time code
1             # Async child handling for RPC::Switch::Client::Tiny
2             #
3             package RPC::Switch::Client::Tiny::Async;
4              
5 22     22   180868 use strict;
  22         64  
  22         636  
6 22     22   131 use warnings;
  22         44  
  22         691  
7 22     22   1522 use IO::Socket;
  22         60599  
  22         147  
8 22     22   13343 use Time::HiRes qw(time);
  22         1416  
  22         135  
9 22     22   3626 use POSIX ":sys_wait_h"; # WNOHANG
  22         18691  
  22         421  
10              
11             our $VERSION = 1.20;
12              
13             sub new {
14 69     69 0 3252 my ($class, %args) = @_;
15 69         1246 return bless {
16             %args,
17             jobqueue => [], # queued async messages
18             jobs => {}, # active async childs
19             finished => {}, # finished childs to reap
20             }, $class;
21             }
22              
23             sub child_stop {
24 152     152 0 1859 my ($self, $pid, $status) = @_;
25 152         690 my $child = $self->{finished}{$pid};
26 152         526 my ($rc, $sig, $core) = ($status >> 8, $status & 127, $status & 128);
27 152         4799 my $stoptime = sprintf "%.02f", time() - $child->{start};
28 152 100       1111 my %runtime = (exists $child->{runtime}) ? (runtime => $child->{runtime}) : ();
29 152 100       678 my %id = (exists $child->{id}) ? (id => $child->{id}) : ();
30 152         407 my %reason = ();
31              
32 152 50 66     2775 if ($^O eq 'MSWin32') { # cpantester: strawberry perl does not support WIF calls
    50          
    100          
    100          
33 0         0 %reason = (reason => $child->{state});
34             } elsif (WIFSTOPPED($status)) {
35 0         0 warn "worker child $pid stopped\n";
36 0         0 return 0;
37             } elsif (WIFSIGNALED($status)) {
38 4         19 %reason = (reason => "killed by signal $sig");
39             } elsif (WIFEXITED($status) && $rc) {
40 14         238 %reason = (reason => "exited with status $rc");
41             } else {
42 134         667 %reason = (reason => $child->{state});
43             }
44 152 100       1045 $self->{trace_cb}->('END', {pid => $pid, %id, %runtime, stoptime => $stoptime, %reason}) if $self->{trace_cb};
45 152         4577 delete $self->{finished}{$pid};
46 152         1428 return 1;
47             }
48              
49             sub childs_reap {
50 635     635 0 6502 my ($self, %opts) = @_;
51 635 100       1834 my $flags = $opts{nonblock} ? WNOHANG : 0;
52              
53             # A child is moved to the finished state in these cases:
54             # 1) The child sent a valid reply on the pipe (done)
55             # 2) The child sent an invalid reply or the pipe closed (error)
56             # 3) The worker closes the pipe after rpcswitch.channel_gone (gone)
57             # 4) The worker closes the pipe after rpcswitch socket closed (stopped)
58             #
59 635         1002 foreach my $child (values %{$self->{finished}}) {
  635         2626  
60 544         41487039 my $res = waitpid($child->{pid}, $flags);
61 544 100       2801 if ($res == 0) {
    50          
62 392         1376 my $waittime = time() - $child->{start};
63              
64             # First try to send maskable signal to give child a
65             # chance to cleanup resources, and send nonmaskable
66             # sigkill to terminate child only after that.
67             # (note: some nfs-syscalls might block nevertheless)
68             # (note: sigkill on windows might deadlock - see below)
69             #
70 392 50 33     2590 if (($waittime > 2) && ($child->{state} ne 'kill') && ($^O ne 'MSWin32')) {
    50 33        
      33        
71 0         0 warn "worker child $child->{pid}: still running after $child->{state} - send kill\n";
72 0         0 kill 'KILL', $child->{pid};
73 0         0 $child->{state} = 'kill';
74             } elsif (($waittime > 1) && ($child->{state} ne 'term')) {
75 0         0 warn "worker child $child->{pid}: still running after $child->{state} - send term\n";
76 0         0 kill 'TERM', $child->{pid};
77 0         0 $child->{state} = 'term';
78             }
79             } elsif ($res < 0) {
80 0 0 0     0 return 0 if (($flags == 0) && $!{EINTR}); # blocking waitpid might be interrupted by signal
81 0 0       0 warn "worker child $child->{pid}: disappeared" unless ($^O eq 'MSWin32');
82 0         0 $self->child_stop($child->{pid}, 0);
83             } else {
84 152         1545 $self->child_stop($child->{pid}, $?);
85             }
86             }
87 635         2100 return 1;
88             }
89              
90             # For perl on windows the perlfork emulation for threading systems
91             # will be used internally (see: https://perldoc.perl.org/perlfork).
92             #
93             # The description of kill() notes that using sig-KILL the process
94             # which implements the pseudo-processes can be blocked and the perl
95             # interpreter hangs.
96             #
97             # -> this behavior is seen even on current win10/2023 systems with
98             # an interpreter like strawberry-perl-5.32.1-64bit (cpan testers).
99             #
100             # This should not happen for sig-TERM, where the perlfork-emulation
101             # will not try to wait on childs and leak resources to avoid deadlocks.
102             #
103             # So the Async module should be avoided on windows, because it will
104             # not work as desired.
105             #
106             sub _childs_term {
107 0     0   0 my ($self) = @_;
108              
109 0         0 foreach my $child (values %{$self->{finished}}) {
  0         0  
110 0 0       0 if ($child->{state} ne 'term') {
111 0         0 warn "worker child $child->{pid}: still running after $child->{state} - force term\n";
112 0         0 kill 'TERM', $child->{pid};
113 0         0 $child->{state} = 'term';
114             }
115             }
116 0         0 return;
117             }
118              
119             sub childs_kill {
120 96     96 0 430 my ($self) = @_;
121              
122 96 50       510 return $self->_childs_term() if ($^O eq 'MSWin32');
123              
124 96         215 foreach my $child (values %{$self->{finished}}) {
  96         565  
125 4 50       13 if ($child->{state} ne 'kill') {
126 4         121 kill 'KILL', $child->{pid}; # terminate non maskable
127 4         26 $child->{state} = 'kill';
128             }
129             }
130 96         2875 return;
131             }
132              
133             sub job_add {
134 181     181 0 844 my ($self, $child, $msg_id, $meta) = @_;
135              
136 181         501 $child->{id} = $msg_id;
137 181         784 $child->{start} = time();
138 181         1015 @$child{keys %$meta} = values %$meta;
139 181         5704 $self->{jobs}{$child->{reader}->fileno} = $child;
140 181         9042 return;
141             }
142              
143             sub job_rem {
144 170     170 0 501 my ($self, $child) = @_;
145              
146 170         4305 $child->{runtime} = sprintf "%.02f", time() - $child->{start};
147 170         872 $child->{start} = time();
148 170         631 delete $self->{jobs}{$child->{reader}->fileno};
149 170         1774 return;
150             }
151              
152             sub child_finish {
153 165     165 0 3274 my ($self, $child, $state) = @_;
154              
155             # The pipe close raises a sigpipe in the child
156             # when the child is still alive and tries to write.
157             #
158 165 50       2158 shutdown($child->{reader}, 2) or warn "worker child $child->{pid}: shutdown pipe failed: $!\n";
159 165 50       3654 close($child->{reader}) or warn "worker child $child->{pid}: close pipe failed: $!\n";
160 165         670 delete $child->{reader};
161              
162 165         1257 $child->{state} = $state;
163 165         699 $child->{start} = time();
164 165         1390 $self->{finished}{$child->{pid}} = $child;
165 165         890 return 1;
166             }
167              
168             sub child_start {
169 195     195 0 629 my ($self, $worker, $msg_id, $msg_vci) = @_;
170 195 100       786 my %id = (defined $msg_id) ? (id => $msg_id) : ();
171 195 100       753 my %vci = (defined $msg_vci) ? (vci => $msg_vci) : ();
172              
173             # Handle waitpid() explicitly instead of using open('-|');
174             # see: https://perldoc.perl.org/perlipc#Safe-Pipe-Opens
175             #
176 195 50       12999 socketpair(my $rd, my $wr, AF_UNIX, SOCK_STREAM, PF_UNSPEC) or die "socketpair failed: $!";
177              
178 195         190929 my $pid = fork();
179 195 50       5023 die "failed to fork: $!" unless defined $pid;
180              
181 195 100       4052 if ($pid != 0) { # parent
182 176         19232 my $child = {reader => $rd, pid => $pid, start => time(), %id};
183 176 100       5897 $self->{trace_cb}->('RUN', {pid => $pid, %id, %vci}) if $self->{trace_cb};
184 176         14512 close($wr);
185 176         16289 return $child;
186             }
187 19         1836 close($rd);
188 19         1333 $self->{jobqueue} = [];
189 19         1751 $self->{jobs} = {};
190 19         865 $self->{finished} = {};
191 19         1498 local $SIG{TERM} = 'DEFAULT';
192              
193             # The child_handler returns an error code or dies.
194             #
195 19         1183 my $ret = $worker->child_handler($wr);
196 18         15644 exit $ret;
197             }
198              
199             sub msg_enqueue {
200 205     205 0 987 my ($self, $msg) = @_;
201              
202             # queue message and start child from rpc_handler
203 205         412 push(@{$self->{jobqueue}}, $msg);
  205         495  
204 205         526 return;
205             }
206              
207             sub msg_dequeue {
208 784     784 0 2194 my ($self) = @_;
209              
210 784 100       1261 unless (keys %{$self->{jobs}} < $self->{max_async}) {
  784         2979  
211 140         1029 return; # wait until job slot is avail
212             }
213 644         1144 return shift(@{$self->{jobqueue}});
  644         2435  
214             }
215              
216             sub jobs_terminate {
217 49     49 0 1289 my ($self, $state, $filter) = @_;
218              
219             # Terminate active jobs & queued jobs
220             # (no error reply since channel is closed)
221             #
222 49         222 my @childs = grep { $filter->($_) } values %{$self->{jobs}};
  4         36  
  49         344  
223 49         430 foreach my $child (@childs) {
224 4         27 $self->job_rem($child);
225 4         20 $self->child_finish($child, $state);
226             }
227 49         241 my @msgs = grep { $filter->($_) } @{$self->{jobqueue}};
  2         8  
  49         198  
228 49 100       201 if (@msgs) {
229 1         14 $self->{jobqueue} = [grep { !$filter->($_) } @{$self->{jobqueue}}];
  2         16  
  1         4  
230             }
231 49         281 return (\@childs, \@msgs);
232             }
233              
234             1;
235              
236             __END__