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   180042 use strict;
  22         62  
  22         620  
6 22     22   129 use warnings;
  22         51  
  22         689  
7 22     22   1595 use IO::Socket;
  22         61831  
  22         181  
8 22     22   14421 use Time::HiRes qw(time);
  22         1365  
  22         136  
9 22     22   3525 use POSIX ":sys_wait_h"; # WNOHANG
  22         18674  
  22         552  
10              
11             our $VERSION = 1.20;
12              
13             sub new {
14 69     69 0 3087 my ($class, %args) = @_;
15 69         1458 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 1273 my ($self, $pid, $status) = @_;
25 152         590 my $child = $self->{finished}{$pid};
26 152         512 my ($rc, $sig, $core) = ($status >> 8, $status & 127, $status & 128);
27 152         4491 my $stoptime = sprintf "%.02f", time() - $child->{start};
28 152 100       878 my %runtime = (exists $child->{runtime}) ? (runtime => $child->{runtime}) : ();
29 152 100       743 my %id = (exists $child->{id}) ? (id => $child->{id}) : ();
30 152         302 my %reason = ();
31              
32 152 50 66     2782 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         17 %reason = (reason => "killed by signal $sig");
39             } elsif (WIFEXITED($status) && $rc) {
40 14         196 %reason = (reason => "exited with status $rc");
41             } else {
42 134         637 %reason = (reason => $child->{state});
43             }
44 152 100       1056 $self->{trace_cb}->('END', {pid => $pid, %id, %runtime, stoptime => $stoptime, %reason}) if $self->{trace_cb};
45 152         3788 delete $self->{finished}{$pid};
46 152         1269 return 1;
47             }
48              
49             sub childs_reap {
50 632     632 0 6327 my ($self, %opts) = @_;
51 632 100       2130 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 632         1239 foreach my $child (values %{$self->{finished}}) {
  632         2999  
60 530         41202859 my $res = waitpid($child->{pid}, $flags);
61 530 100       2545 if ($res == 0) {
    50          
62 378         1199 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 378 50 33     2437 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         1281 $self->child_stop($child->{pid}, $?);
85             }
86             }
87 632         2352 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 260 my ($self) = @_;
121              
122 96 50       374 return $self->_childs_term() if ($^O eq 'MSWin32');
123              
124 96         286 foreach my $child (values %{$self->{finished}}) {
  96         664  
125 4 50       13 if ($child->{state} ne 'kill') {
126 4         121 kill 'KILL', $child->{pid}; # terminate non maskable
127 4         30 $child->{state} = 'kill';
128             }
129             }
130 96         2175 return;
131             }
132              
133             sub job_add {
134 181     181 0 1262 my ($self, $child, $msg_id, $meta) = @_;
135              
136 181         550 $child->{id} = $msg_id;
137 181         794 $child->{start} = time();
138 181         921 @$child{keys %$meta} = values %$meta;
139 181         5146 $self->{jobs}{$child->{reader}->fileno} = $child;
140 181         9698 return;
141             }
142              
143             sub job_rem {
144 169     169 0 606 my ($self, $child) = @_;
145              
146 169         5205 $child->{runtime} = sprintf "%.02f", time() - $child->{start};
147 169         1013 $child->{start} = time();
148 169         842 delete $self->{jobs}{$child->{reader}->fileno};
149 169         1954 return;
150             }
151              
152             sub child_finish {
153 164     164 0 4948 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 164 50       2422 shutdown($child->{reader}, 2) or warn "worker child $child->{pid}: shutdown pipe failed: $!\n";
159 164 50       3653 close($child->{reader}) or warn "worker child $child->{pid}: close pipe failed: $!\n";
160 164         793 delete $child->{reader};
161              
162 164         1358 $child->{state} = $state;
163 164         749 $child->{start} = time();
164 164         1496 $self->{finished}{$child->{pid}} = $child;
165 164         899 return 1;
166             }
167              
168             sub child_start {
169 195     195 0 583 my ($self, $worker, $msg_id, $msg_vci) = @_;
170 195 100       800 my %id = (defined $msg_id) ? (id => $msg_id) : ();
171 195 100       616 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       12568 socketpair(my $rd, my $wr, AF_UNIX, SOCK_STREAM, PF_UNSPEC) or die "socketpair failed: $!";
177              
178 195         199474 my $pid = fork();
179 195 50       5458 die "failed to fork: $!" unless defined $pid;
180              
181 195 100       4082 if ($pid != 0) { # parent
182 176         18089 my $child = {reader => $rd, pid => $pid, start => time(), %id};
183 176 100       6021 $self->{trace_cb}->('RUN', {pid => $pid, %id, %vci}) if $self->{trace_cb};
184 176         15337 close($wr);
185 176         17637 return $child;
186             }
187 19         1712 close($rd);
188 19         1248 $self->{jobqueue} = [];
189 19         1712 $self->{jobs} = {};
190 19         721 $self->{finished} = {};
191 19         1612 local $SIG{TERM} = 'DEFAULT';
192              
193             # The child_handler returns an error code or dies.
194             #
195 19         1240 my $ret = $worker->child_handler($wr);
196 18         13513 exit $ret;
197             }
198              
199             sub msg_enqueue {
200 205     205 0 840 my ($self, $msg) = @_;
201              
202             # queue message and start child from rpc_handler
203 205         384 push(@{$self->{jobqueue}}, $msg);
  205         576  
204 205         524 return;
205             }
206              
207             sub msg_dequeue {
208 781     781 0 2879 my ($self) = @_;
209              
210 781 100       1643 unless (keys %{$self->{jobs}} < $self->{max_async}) {
  781         3833  
211 137         920 return; # wait until job slot is avail
212             }
213 644         1260 return shift(@{$self->{jobqueue}});
  644         2740  
214             }
215              
216             sub jobs_terminate {
217 49     49 0 1406 my ($self, $state, $filter) = @_;
218              
219             # Terminate active jobs & queued jobs
220             # (no error reply since channel is closed)
221             #
222 49         219 my @childs = grep { $filter->($_) } values %{$self->{jobs}};
  4         26  
  49         330  
223 49         416 foreach my $child (@childs) {
224 4         38 $self->job_rem($child);
225 4         16 $self->child_finish($child, $state);
226             }
227 49         178 my @msgs = grep { $filter->($_) } @{$self->{jobqueue}};
  2         7  
  49         247  
228 49 100       231 if (@msgs) {
229 1         8 $self->{jobqueue} = [grep { !$filter->($_) } @{$self->{jobqueue}}];
  2         17  
  1         4  
230             }
231 49         313 return (\@childs, \@msgs);
232             }
233              
234             1;
235              
236             __END__