git.iko.soy/typeable/nixpkgs
on master help sign in
Merge pull request #32992 from nh2/fix-32545-blocking-container-destroy

nixos-container: Fix `destroy` terminating before it's done. Fixes #32545

commit5461e72cc903aafdfc1c60821462b101085977fe authorFranz Pletz <fpletz@fnordicwalking.de> dateMon 12 Mar 2018, 21:27 (9 years ago) parentce23a715d83988
1 file changed+18−8
pkgs/tools/virtualization/nixos-container/nixos-container.pl+18−8
pkgs/tools/virtualization/nixos-container/nixos-container.pl+18−8
@@ -7,6 +7,7 @@ use File::Slurp;
77use Fcntl ':flock';
88use Getopt::Long qw(:config gnu_getopt);
99use Cwd 'abs_path';
10+use Time::HiRes;
1011
1112my $nsenter = "@utillinux@/bin/nsenter";
1213my $su = "@su@";
@@ -214,14 +215,31 @@ if (!-e $confFile) {
214215 die "$0: container ‘$containerName’ does not exist\n" ;
215216}
216217
218+# Return the PID of the init process of the container.
219+sub getLeader {
220+ my $s = `machinectl show "$containerName" -p Leader`;
221+ chomp $s;
222+ $s =~ /^Leader=(\d+)$/ or die "unable to get container's main PID\n";
223+ return int($1);
224+}
225+
217226sub isContainerRunning {
218227 my $status = `systemctl show 'container\@$containerName'`;
219228 return $status =~ /ActiveState=active/;
220229}
221230
222231sub terminateContainer {
232+ my $leader = getLeader;
223233 system("machinectl", "terminate", $containerName) == 0
224234 or die "$0: failed to terminate container\n";
235+ # Wait for the leader process to exit
236+ # TODO: As for any use of PIDs for process control where the process is
237+ # not a direct child of ours, this can go wrong when the pid gets
238+ # recycled after a PID overflow.
239+ # Relying entirely on some form of UUID provided by machinectl
240+ # instead of PIDs would remove this risk.
241+ # See https://github.com/NixOS/nixpkgs/pull/32992#discussion_r158586048
242+ while ( kill 0, $leader ) { Time::HiRes::sleep(0.1) }
225243}
226244
227245sub stopContainer {
@@ -229,14 +247,6 @@ sub stopContainer {
229247 or die "$0: failed to stop container\n";
230248}
231249
232−# Return the PID of the init process of the container.
233−sub getLeader {
234− my $s = `machinectl show "$containerName" -p Leader`;
235− chomp $s;
236− $s =~ /^Leader=(\d+)$/ or die "unable to get container's main PID\n";
237− return int($1);
238−}
239−
240250# Run a command in the container.
241251sub runInContainer {
242252 my @args = @_;