]> git.proxmox.com Git - pve-installer.git/blob - Proxmox/Sys/Command.pm
sys: wait a second after sending TERM signal before going for KILL
[pve-installer.git] / Proxmox / Sys / Command.pm
1 package Proxmox::Sys::Command;
2
3 use strict;
4 use warnings;
5
6 use Carp;
7 use IO::File;
8 use IPC::Open3;
9 use IO::Select;
10 use String::ShellQuote;
11 use POSIX ":sys_wait_h";
12
13 use Proxmox::Install::ISOEnv;
14 use Proxmox::Log;
15 use Proxmox::UI;
16
17 use base qw(Exporter);
18 our @EXPORT_OK = qw(run_command syscmd CMD_FINISHED);
19
20 use constant CMD_FINISHED => 1;
21
22 my sub shellquote {
23 my $str = shift;
24 return String::ShellQuote::shell_quote($str);
25 }
26
27 my sub cmd2string {
28 my ($cmd) = @_;
29
30 die "no arguments" if !$cmd;
31 return $cmd if !ref($cmd);
32
33 my $quoted_args = [ map { shellquote($_) } $cmd->@* ];
34
35 return join (' ', $quoted_args->@*);
36 }
37
38 # Safely for the (sub-)process specified by $pid to exit, using a timeout.
39 #
40 # When kill => 1 is set, at first a TERM-signal is sent to the process before
41 # checking if it exited.
42 # If that fails, KILL is sent to process and then up to timeout => $timeout
43 # seconds (default: 5) are waited for the process to exit.
44 #
45 # On sucess, the exitcode of the process is returned, otherwise `undef` (aka.
46 # the process was unkillable).
47 my sub wait_for_process {
48 my ($pid, %params) = @_;
49
50 kill('TERM', $pid) if $params{kill};
51
52 my $timeout = $params{timeout} // 5;
53 for (0 .. $timeout) {
54 my $terminated = waitpid($pid, WNOHANG);
55 return $? if $terminated > 0;
56
57 sleep(1) if $_ != $timeout; # all but last round
58 kill('KILL', $pid) if $params{kill} && $_ == 1; # just first round
59 }
60
61 log_warn("failed to kill child pid $pid, probably stuck in D-state?\n");
62
63 # We tried our best, better let the child hang in the back then completely
64 # blocking installer progress .. it's a rather short-lived environment anyway
65 }
66
67 sub syscmd {
68 my ($cmd) = @_;
69
70 return run_command($cmd, undef, undef, 1);
71 }
72
73 # Runs a command an a subprocess, properly handling IO via piping, cleaning up and passing back the
74 # exit code.
75 #
76 # If $cmd contains a pipe |, the command will be executed inside a bash shell.
77 # If $cmd contains 'chpasswd', the input will be specially quoted for that purpose.
78 #
79 # Arguments:
80 # * $cmd - The command to run, either a single string or array with individual arguments
81 # * $func - Logging subroutine to call, receives both stdout and stderr. Might return CMD_FINISHED
82 # to exit early and ignore the rest of the process output.
83 # * $input - Stdin contents for the spawned subprocess
84 # * $noout - Whether to append any process output to the return value
85 # * $noprint - Whether to print any process output to the parents stdout
86 sub run_command {
87 my ($cmd, $func, $input, $noout, $noprint) = @_;
88
89 my $cmdstr;
90 if (!ref($cmd)) {
91 $cmdstr = $cmd;
92 if ($cmd =~ m/|/) {
93 # see 'man bash' for option pipefail
94 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
95 } else {
96 $cmd = [ $cmd ];
97 }
98 } else {
99 $cmdstr = cmd2string($cmd);
100 }
101
102 my $cmdtxt;
103 if ($input && ($cmdstr !~ m/chpasswd/)) {
104 $cmdtxt = "# $cmdstr <<EOD\n$input";
105 chomp $cmdtxt;
106 $cmdtxt .= "\nEOD\n";
107 } else {
108 $cmdtxt = "# $cmdstr\n";
109 }
110
111 if (is_test_mode()) {
112 print $cmdtxt;
113 STDOUT->flush();
114 }
115 log_info($cmdtxt);
116
117 my ($reader, $writer, $error) = (IO::File->new(), IO::File->new(), IO::File->new());
118
119 my $orig_pid = $$;
120
121 my $pid = eval { open3($writer, $reader, $error, @$cmd) || die $!; };
122 my $err = $@;
123
124 if ($orig_pid != $$) { # catch exec errors
125 POSIX::_exit (1);
126 kill ('KILL', $$);
127 }
128 die $err if $err;
129
130 print $writer $input if defined $input;
131 close $writer;
132
133 my $select = IO::Select->new();
134 $select->add($reader);
135 $select->add($error);
136
137 my ($ostream, $logout) = ('', '', '');
138 my $caught_sig;
139
140 while ($select->count) {
141 my @handles = $select->can_read (0.2);
142
143 # If we catch a signal, stop processing & clean up
144 if ($!{EINTR}) {
145 $caught_sig = 1;
146 last;
147 }
148
149 Proxmox::UI::process_events();
150
151 next if !scalar (@handles); # timeout
152
153 foreach my $h (@handles) {
154 my $buf = '';
155 my $count = sysread ($h, $buf, 4096);
156 if (!defined ($count)) {
157 my $err = $!;
158 wait_for_process($pid, kill => 1);
159 die "command '$cmd' failed: $err";
160 }
161 $select->remove($h) if !$count;
162 if ($h eq $reader) {
163 $ostream .= $buf if !($noout || $func);
164 $logout .= $buf;
165 while ($logout =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
166 my $line = $1;
167 if ($func) {
168 my $ret = $func->($line);
169 if (defined($ret) && $ret == CMD_FINISHED) {
170 wait_for_process($pid, kill => 1);
171 return $ostream;
172 }
173 };
174 }
175
176 } elsif ($h eq $error) {
177 $ostream .= $buf if !($noout || $func);
178 }
179 print $buf if !$noprint;
180 STDOUT->flush();
181 log_info($buf);
182 }
183 }
184
185 &$func($logout) if $func;
186
187 my $ec = wait_for_process($pid, kill => $caught_sig);
188
189 # behave like standard system(); returns -1 in case of errors too
190 return ($ec // -1) if $noout;
191
192 if (!defined($ec)) {
193 # Don't fail completely here to let the install continue
194 warn "command '$cmdstr' failed to exit properly\n";
195 } elsif ($ec == -1) {
196 croak "command '$cmdstr' failed to execute\n";
197 } elsif (my $sig = ($ec & 127)) {
198 croak "command '$cmdstr' failed - got signal $sig\n";
199 } elsif (my $exitcode = ($ec >> 8)) {
200 croak "command '$cmdstr' failed with exit code $exitcode";
201 }
202
203 return $ostream;
204 }
205
206 # forks and runs the provided coderef in the child
207 # do not use syscmd or run_command as both confuse the GTK mainloop if
208 # run from a child process
209 sub run_in_background {
210 my ($cmd) = @_;
211
212 my $pid = fork() // die "fork failed: $!\n";
213 if (!$pid) {
214 eval { $cmd->(); };
215 if (my $err = $@) {
216 warn "run_in_background error: $err\n";
217 POSIX::_exit(1);
218 }
219 POSIX::_exit(0);
220 }
221 }
222
223 1;