lei/store: stop shard workers + cat-file on idle
[public-inbox.git] / t / spawn.t
blob45517852da70b3a2879ba77bc9deeaabe128a45d
1 #!perl -w
2 # Copyright (C) all contributors <meta@public-inbox.org>
3 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 use v5.12;
5 use Test::More;
6 use PublicInbox::Spawn qw(which spawn popen_rd run_qx);
7 require PublicInbox::Sigfd;
8 require PublicInbox::DS;
9 use PublicInbox::OnDestroy;
10 my $rlimit_map = PublicInbox::Spawn->can('rlimit_map');
12         my $true = which('true');
13         ok($true, "'true' command found with which()");
17         my $pid = spawn(['true']);
18         ok($pid, 'spawned process');
19         is(waitpid($pid, 0), $pid, 'waitpid succeeds on spawned process');
20         is($?, 0, 'true exited successfully');
24         my $opt = { 0 => \'in', 2 => \(my $e) };
25         my $out = run_qx(['sh', '-c', 'echo e >&2; cat'], undef, $opt);
26         is($e, "e\n", 'captured stderr');
27         is($out, 'in', 'stdin read and stdout captured');
28         $opt->{0} = \"IN\n3\nLINES";
29         my @out = run_qx(['sh', '-c', 'echo E >&2; cat'], undef, $opt);
30         is($e, "E\n", 'captured stderr clobbers string');
31         is_deeply(\@out, [ "IN\n", "3\n", 'LINES' ], 'stdout array');
34 SKIP: {
35         my $pid = spawn(['true'], undef, { pgid => 0 });
36         ok($pid, 'spawned process with new pgid');
37         is(waitpid($pid, 0), $pid, 'waitpid succeeds on spawned process');
38         is($?, 0, 'true exited successfully');
39         pipe(my ($r, $w)) or BAIL_OUT;
41         # Find invalid PID to try to join its process group.
42         my $wrong_pgid = 1;
43         for (my $i=0x7fffffff; $i >= 2; $i--) {
44                 if (kill(0, $i) == 0) {
45                         $wrong_pgid = $i;
46                         last;
47                 }
48         }
50         # Test spawn behavior when it can't join the requested process group.
51         $pid = eval { spawn(['true'], undef, { pgid => $wrong_pgid, 2 => $w }) };
52         close $w;
53         my $err = do { local $/; <$r> };
54         if (defined $pid) {
55                 waitpid($pid, 0);
56                 isnt($?, 0, 'child error (pure-Perl)');
57         } else {
58                 ok($@, 'exception raised');
59         }
62 { # ensure waitpid(-1, 0) and SIGCHLD works in spawned process
63         my $script = <<'EOF';
64 $| = 1; # unbuffer stdout
65 defined(my $pid = fork) or die "fork: $!";
66 if ($pid == 0) { exit }
67 elsif ($pid > 0) {
68         my $waited = waitpid(-1, 0);
69         $waited == $pid or die "mismatched child $pid != $waited";
70         $? == 0 or die "child err: $>";
71         $SIG{CHLD} = sub { print "HI\n"; exit };
72         print "RDY $$\n";
73         select(undef, undef, undef, 0.01) while 1;
75 EOF
76         my $oldset = PublicInbox::DS::block_signals();
77         my $rd = popen_rd([$^X, qw(-w -e), $script]);
78         diag 'waiting for child to reap grandchild...';
79         chomp(my $line = readline($rd));
80         my ($rdy, $pid) = split(/ /, $line);
81         is($rdy, 'RDY', 'got ready signal, waitpid(-1) works in child');
82         ok(kill('CHLD', $pid), 'sent SIGCHLD to child');
83         is(readline($rd), "HI\n", '$SIG{CHLD} works in child');
84         ok($rd->close, 'popen_rd close works');
85         PublicInbox::DS::sig_setmask($oldset);
89         my ($r, $w);
90         pipe $r, $w or die "pipe failed: $!";
91         my $pid = spawn(['echo', 'hello world'], undef, { 1 => fileno($w) });
92         close $w or die "close pipe[1] failed: $!";
93         is(<$r>, "hello world\n", 'read stdout of spawned from pipe');
94         is(waitpid($pid, 0), $pid, 'waitpid succeeds on spawned process');
95         is($?, 0, 'true exited successfully');
99         my ($r, $w);
100         pipe $r, $w or die "pipe failed: $!";
101         my $pid = spawn(['sh', '-c', 'echo $HELLO'],
102                 { 'HELLO' => 'world' }, { 1 => $w });
103         close $w or die "close pipe[1] failed: $!";
104         is(<$r>, "world\n", 'read stdout of spawned from pipe');
105         is(waitpid($pid, 0), $pid, 'waitpid succeeds on spawned process');
106         is($?, 0, 'sh exited successfully');
110         my $fh = popen_rd([qw(echo hello)]);
111         ok(fileno($fh) >= 0, 'fileno works');
112         my $l = <$fh>;
113         is($l, "hello\n", 'readline works');
114         $l = <$fh>;
115         ok(!$l, 'readline works for EOF');
119         my $fh = popen_rd([qw(printf foo\nbar)]);
120         ok(fileno($fh) >= 0, 'fileno works');
121         is($fh->blocking(0), 1, '->blocking was true');
122         is($fh->blocking, 0, '->blocking is false');
123         is($fh->blocking(1), 0, '->blocking was true');
124         is($fh->blocking, 1, '->blocking is true');
125         my @line = <$fh>;
126         is_deeply(\@line, [ "foo\n", 'bar' ], 'wantarray works on readline');
130         my $fh = popen_rd([qw(echo hello)]);
131         like($fh->attached_pid, qr/\A[0-9]+\z/, 'have a PID');
132         my $buf;
133         is(sysread($fh, $buf, 6), 6, 'sysread got 6 bytes');
134         is($buf, "hello\n", 'sysread works');
135         is(sysread($fh, $buf, 6), 0, 'sysread got EOF');
136         $? = 1;
137         ok($fh->close, 'close succeeds');
138         is($?, 0, '$? set properly');
139         is($fh->attached_pid, undef, 'attached_pid cleared after close');
143         my $fh = popen_rd([qw(false)]);
144         ok(!$fh->close, 'close fails on false');
145         isnt($?, 0, '$? set properly: '.$?);
149         local $ENV{GIT_CONFIG} = '/path/to/this/better/not/exist';
150         my $fh = popen_rd([qw(env)], { GIT_CONFIG => undef });
151         ok(!grep(/^GIT_CONFIG=/, <$fh>), 'GIT_CONFIG clobbered');
154 { # ->CLOSE vs ->DESTROY waitpid caller distinction
155         my @c;
156         my $fh = popen_rd(['true'], undef, undef, sub { @c = caller });
157         ok($fh->close, '->CLOSE fired and successful');
158         ok(scalar(@c), 'callback fired by ->CLOSE');
159         ok(grep(!m[/PublicInbox/DS\.pm\z], @c), 'callback not invoked by DS');
161         @c = ();
162         $fh = popen_rd(['true'], undef, undef, sub { @c = caller });
163         undef $fh; # ->DESTROY
164         ok(scalar(@c), 'callback fired by ->DESTROY');
165         ok(grep(!m[/PublicInbox/IO\.pm\z], @c),
166                 'callback not invoked by PublicInbox::IO');
169 { # children don't wait on siblings
170         use POSIX qw(_exit);
171         pipe(my ($r, $w)) or BAIL_OUT $!;
172         my @arg;
173         my $fh = popen_rd(['cat'], undef, { 0 => $r },
174                         sub { @arg = @_; warn "x=$$\n" }, 'hi');
175         my $pid = PublicInbox::OnDestroy::fork_tmp;
176         local $SIG{__WARN__} = sub { _exit(1) };
177         if ($pid == 0) {
178                 local $SIG{__DIE__} = sub { _exit(2) };
179                 undef $fh;
180                 _exit(0);
181         }
182         waitpid($pid, 0);
183         is($?, 0, 'forked process exited');
184         my @w;
185         local $SIG{__WARN__} = sub { push @w, @_ };
186         close $w;
187         $fh->close; # may set $?
188         is($?, 0, 'cat exited');
189         is(scalar(@arg), 2, 'callback got args');
190         is($arg[1], 'hi', 'passed arg');
191         like($arg[0], qr/\A\d+\z/, 'PID');
192         is_deeply(\@w, [ "x=$$\n" ], 'callback fired from owner');
195 SKIP: {
196         if ($rlimit_map) { # Inline::C installed
197                 my %rlim = $rlimit_map->();
198                 ok defined($rlim{RLIMIT_CPU}), 'RLIMIT_CPU defined';
199         } else {
200                 eval {
201                         require BSD::Resource;
202                         defined(BSD::Resource::RLIMIT_CPU())
203                 } or skip 'BSD::Resource::RLIMIT_CPU missing', 3;
204         }
205         my $cmd = [ $^X, qw(-w -e), <<'EOM' ];
206 use POSIX qw(:signal_h);
207 use Time::HiRes qw(time); # gettimeofday
208 my $have_bsd_resource = eval { require BSD::Resource };
209 my $set = POSIX::SigSet->new;
210 $set->emptyset; # spawn() defaults to blocking all signals
211 sigprocmask(SIG_SETMASK, $set) or die "SIG_SETMASK: $!";
212 my $tot = 0;
213 $SIG{XCPU} = sub { print "SIGXCPU $tot\n"; exit(1) };
214 my $next = time + 1.1;
215 while (1) {
216         # OpenBSD needs some syscalls (e.g. `times', `gettimeofday'
217         # and `write' (via Perl warn)) on otherwise idle systems to
218         # hit RLIMIT_CPU and fire signals:
219         # https://marc.info/?i=02A4BB8D-313C-464D-845A-845EB6136B35@gmail.com
220         my @t = $have_bsd_resource ? BSD::Resource::times() : (0, 0);
221         $tot = $t[0] + $t[1];
222         if (time > $next) {
223                 warn "# T: @t (utime, ctime, cutime, cstime)\n" if @t;
224                 $next = time + 1.1;
225         }
228         pipe(my($r, $w)) or die "pipe: $!";
229         my $fd = fileno($w);
230         my $opt = { RLIMIT_CPU => [ 1, 9 ], RLIMIT_CORE => [ 0, 0 ], 1 => $fd };
231         my $pid = spawn($cmd, undef, $opt);
232         close $w or die "close(w): $!";
233         my $rset = '';
234         vec($rset, fileno($r), 1) = 1;
235         ok(select($rset, undef, undef, 5), 'child died before timeout');
236         is(waitpid($pid, 0), $pid, 'XCPU child process reaped');
237         my $line;
238         like($line = readline($r), qr/SIGXCPU/, 'SIGXCPU handled') or
239                 diag explain($line);
240         is($? >> 8, 1, 'non-zero exit status');
243 SKIP: {
244         require PublicInbox::SpawnPP;
245         require File::Temp;
246         my $tmp = File::Temp->newdir('spawnpp-XXXX', TMPDIR => 1);
247         my $cmd = [ qw(/bin/sh -c), 'echo $HI >foo' ];
248         my $env = [ 'HI=hihi' ];
249         my $rlim = [];
250         my $pgid = -1;
251         my $pid = PublicInbox::SpawnPP::pi_fork_exec([], '/bin/sh', $cmd, $env,
252                                                 $rlim, "$tmp", $pgid);
253         is(waitpid($pid, 0), $pid, 'spawned process exited');
254         is($?, 0, 'no error');
255         open my $fh, '<', "$tmp/foo" or die "open: $!";
256         is(readline($fh), "hihi\n", 'env+chdir worked for SpawnPP');
257         close $fh;
258         unlink("$tmp/foo") or die "unlink: $!";
259         {
260                 local $ENV{MOD_PERL} = 1;
261                 $pid = PublicInbox::SpawnPP::pi_fork_exec([],
262                                 '/bin/sh', $cmd, $env, $rlim, "$tmp", $pgid);
263         }
264         is(waitpid($pid, 0), $pid, 'spawned process exited');
265         open $fh, '<', "$tmp/foo" or die "open: $!";
266         is(readline($fh), "hihi\n", 'env+chdir SpawnPP under (faked) MOD_PERL');
269 done_testing();