File Coverage

lib/RPC/Switch/Client/Tiny/Async.pm
Criterion Covered Total %
statement 106 118 89.8
branch 36 50 72.0
condition 4 12 33.3
subroutine 16 16 100.0
pod 0 11 0.0
total 162 207 78.2


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   184317 use strict;
  22         68  
  22         633  
6 22     22   109 use warnings;
  22         44  
  22         753  
7 22     22   1585 use IO::Socket;
  22         62206  
  22         164  
8 22     22   21957 use Time::HiRes qw(time);
  22         1403  
  22         113  
9 22     22   3497 use POSIX ":sys_wait_h"; # WNOHANG
  22         18759  
  22         568  
10              
11             our $VERSION = 1.19;
12              
13             sub new {
14 69     69 0 4490 my ($class, %args) = @_;
15 69         1346 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 1421 my ($self, $pid, $status) = @_;
25 152         785 my $child = $self->{finished}{$pid};
26 152         806 my ($rc, $sig, $core) = ($status >> 8, $status & 127, $status & 128);
27 152         2368 my $stoptime = sprintf "%.02f", time() - $child->{start};
28 152 100       1267 my %runtime = (exists $child->{runtime}) ? (runtime => $child->{runtime}) : ();
29 152 100       674 my %id = (exists $child->{id}) ? (id => $child->{id}) : ();
30 152         3270 my %reason = ();
31              
32 152 50 66     3028 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         294 %reason = (reason => "exited with status $rc");
41             } else {
42 134         799 %reason = (reason => $child->{state});
43             }
44 152 100       1143 $self->{trace_cb}->('END', {pid => $pid, %id, %runtime, stoptime => $stoptime, %reason}) if $self->{trace_cb};
45 152         4098 delete $self->{finished}{$pid};
46 152         1698 return 1;
47             }
48              
49             sub childs_reap {
50 635     635 0 6176 my ($self, %opts) = @_;
51 635 100       1880 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         1149 foreach my $child (values %{$self->{finished}}) {
  635         1933  
60 544         42083489 my $res = waitpid($child->{pid}, $flags);
61 544 100       2575 if ($res == 0) {
    50          
62 392         1561 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             #
69 392 50 33     2479 if (($waittime > 2) && ($child->{state} ne 'kill')) {
    50 33        
70 0         0 warn "worker child $child->{pid}: still running after $child->{state} - send kill\n";
71 0         0 kill 'KILL', $child->{pid};
72 0         0 $child->{state} = 'kill';
73             } elsif (($waittime > 1) && ($child->{state} ne 'term')) {
74 0         0 warn "worker child $child->{pid}: still running after $child->{state} - send term\n";
75 0         0 kill 'TERM', $child->{pid};
76 0         0 $child->{state} = 'term';
77             }
78             } elsif ($res < 0) {
79 0 0 0     0 return 0 if (($flags == 0) && $!{EINTR}); # blocking waitpid might be interrupted by signal
80 0 0       0 warn "worker child $child->{pid}: disappeared" unless ($^O eq 'MSWin32');
81 0         0 $self->child_stop($child->{pid}, 0);
82             } else {
83 152         1612 $self->child_stop($child->{pid}, $?);
84             }
85             }
86 635         2398 return 1;
87             }
88              
89             sub childs_kill {
90 96     96 0 287 my ($self) = @_;
91              
92 96         234 foreach my $child (values %{$self->{finished}}) {
  96         2980  
93 4 50       14 if ($child->{state} ne 'kill') {
94 4         133 kill 'KILL', $child->{pid}; # terminate non maskable
95 4         30 $child->{state} = 'kill';
96             }
97             }
98             }
99              
100             sub job_add {
101 181     181 0 1109 my ($self, $child, $msg_id, $meta) = @_;
102              
103 181         610 $child->{id} = $msg_id;
104 181         720 $child->{start} = time();
105 181         852 @$child{keys %$meta} = values %$meta;
106 181         5027 $self->{jobs}{$child->{reader}->fileno} = $child;
107             }
108              
109             sub job_rem {
110 170     170 0 442 my ($self, $child) = @_;
111              
112 170         4807 $child->{runtime} = sprintf "%.02f", time() - $child->{start};
113 170         790 $child->{start} = time();
114 170         631 delete $self->{jobs}{$child->{reader}->fileno};
115             }
116              
117             sub child_finish {
118 165     165 0 3736 my ($self, $child, $state) = @_;
119              
120             # The pipe close raises a sigpipe in the child
121             # when the child is still alive and tries to write.
122             #
123 165 50       2250 shutdown($child->{reader}, 2) or warn "worker child $child->{pid}: shutdown pipe failed: $!\n";
124 165 50       3707 close($child->{reader}) or warn "worker child $child->{pid}: close pipe failed: $!\n";
125 165         722 delete $child->{reader};
126              
127 165         1462 $child->{state} = $state;
128 165         846 $child->{start} = time();
129 165         1186 $self->{finished}{$child->{pid}} = $child;
130 165         843 return 1;
131             }
132              
133             sub child_start {
134 195     195 0 608 my ($self, $worker, $msg_id, $msg_vci) = @_;
135 195 100       995 my %id = (defined $msg_id) ? (id => $msg_id) : ();
136 195 100       914 my %vci = (defined $msg_vci) ? (vci => $msg_vci) : ();
137              
138             # Handle waitpid() explicitly instead of using open('-|');
139             # see: https://perldoc.perl.org/perlipc#Safe-Pipe-Opens
140             #
141 195 50       13091 socketpair(my $rd, my $wr, AF_UNIX, SOCK_STREAM, PF_UNSPEC) or die "socketpair failed: $!";
142              
143 195         181662 my $pid = fork();
144 195 50       6731 die "failed to fork: $!" unless defined $pid;
145              
146 195 100       4792 if ($pid != 0) { # parent
147 176         18465 my $child = {reader => $rd, pid => $pid, start => time(), %id};
148 176 100       5767 $self->{trace_cb}->('RUN', {pid => $pid, %id, %vci}) if $self->{trace_cb};
149 176         19240 close($wr);
150 176         16779 return $child;
151             }
152 19         1885 close($rd);
153 19         1314 $self->{jobqueue} = [];
154 19         1931 $self->{jobs} = {};
155 19         904 $self->{finished} = {};
156 19         2174 local $SIG{TERM} = 'DEFAULT';
157              
158             # The child_handler returns an error code or dies.
159             #
160 19         1447 my $ret = $worker->child_handler($wr);
161 18         15116 exit $ret;
162             }
163              
164             sub msg_enqueue {
165 205     205 0 630 my ($self, $msg) = @_;
166              
167             # queue message and start child from rpc_handler
168 205         523 push(@{$self->{jobqueue}}, $msg);
  205         835  
169             }
170              
171             sub msg_dequeue {
172 784     784 0 12603 my ($self) = @_;
173              
174 784 100       2550 unless (keys %{$self->{jobs}} < $self->{max_async}) {
  784         2867  
175 140         1425 return; # wait until job slot is avail
176             }
177 644         1866 return shift(@{$self->{jobqueue}});
  644         2647  
178             }
179              
180             sub jobs_terminate {
181 49     49 0 587 my ($self, $state, $filter) = @_;
182              
183             # Terminate active jobs & queued jobs
184             # (no error reply since channel is closed)
185             #
186 49         223 my @childs = grep { $filter->($_) } values %{$self->{jobs}};
  4         38  
  49         344  
187 49         1508 foreach my $child (@childs) {
188 4         24 $self->job_rem($child);
189 4         58 $self->child_finish($child, $state);
190             }
191 49         246 my @msgs = grep { $filter->($_) } @{$self->{jobqueue}};
  2         20  
  49         283  
192 49 100       289 if (@msgs) {
193 1         3 $self->{jobqueue} = [grep { !$filter->($_) } @{$self->{jobqueue}}];
  2         17  
  1         6  
194             }
195 49         411 return (\@childs, \@msgs);
196             }
197              
198             1;
199              
200             __END__