From cb49c1432417f9576ed12613f0374b3bc23587c2 Mon Sep 17 00:00:00 2001 From: Eelco Dolstra Date: Tue, 21 Mar 2017 16:45:47 +0100 Subject: [PATCH] Revert "nixos-container: Use machinectl shell (#18825)" This reverts commit c37e76b4d2ac59139df8956cc2b1ec6921bea11d. Unfortunately, using "machinectl shell" has two bad side effects: * It sends the command's stderr to stdout. * It doesn't propagate the command's exit status. This broke NixOps. PR #18825. --- .../nixos-container/default.nix | 2 ++ .../nixos-container/nixos-container.pl | 23 +++++++++++++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/pkgs/tools/virtualization/nixos-container/default.nix b/pkgs/tools/virtualization/nixos-container/default.nix index 19394ea45d30..0763536533f0 100644 --- a/pkgs/tools/virtualization/nixos-container/default.nix +++ b/pkgs/tools/virtualization/nixos-container/default.nix @@ -6,6 +6,8 @@ substituteAll { isExecutable = true; src = ./nixos-container.pl; perl = "${perl}/bin/perl -I${perlPackages.FileSlurp}/lib/perl5/site_perl"; + su = "${shadow.su}/bin/su"; + inherit utillinux; postInstall = '' t=$out/etc/bash_completion.d diff --git a/pkgs/tools/virtualization/nixos-container/nixos-container.pl b/pkgs/tools/virtualization/nixos-container/nixos-container.pl index 65a9c3f5814b..754715cddd0b 100755 --- a/pkgs/tools/virtualization/nixos-container/nixos-container.pl +++ b/pkgs/tools/virtualization/nixos-container/nixos-container.pl @@ -8,6 +8,9 @@ use Fcntl ':flock'; use Getopt::Long qw(:config gnu_getopt); use Cwd 'abs_path'; +my $nsenter = "@utillinux@/bin/nsenter"; +my $su = "@su@"; + # Ensure a consistent umask. umask 0022; @@ -223,6 +226,22 @@ sub stopContainer { or die "$0: failed to stop container\n"; } +# Return the PID of the init process of the container. +sub getLeader { + my $s = `machinectl show "$containerName" -p Leader`; + chomp $s; + $s =~ /^Leader=(\d+)$/ or die "unable to get container's main PID\n"; + return int($1); +} + +# Run a command in the container. +sub runInContainer { + my @args = @_; + my $leader = getLeader; + exec($nsenter, "-t", $leader, "-m", "-u", "-i", "-n", "-p", "--", @args); + die "cannot run ‘nsenter’: $!\n"; +} + # Remove a directory while recursively unmounting all mounted filesystems within # that directory and unmounting/removing that directory afterwards as well. # @@ -297,14 +316,14 @@ elsif ($action eq "login") { } elsif ($action eq "root-login") { - exec("machinectl", "shell", $containerName, "/bin/sh", "-l"); + runInContainer("@su@", "root", "-l"); } elsif ($action eq "run") { shift @ARGV; shift @ARGV; # Escape command. my $s = join(' ', map { s/'/'\\''/g; "'$_'" } @ARGV); - exec("machinectl", "--quiet", "shell", $containerName, "/bin/sh", "-l", "-c", $s); + runInContainer("@su@", "root", "-l", "-c", "exec " . $s); } elsif ($action eq "show-ip") {