Skip to content

Commit

Permalink
nixos-container: Use machinectl shell (NixOS#18825)
Browse files Browse the repository at this point in the history
Using nsenter+su was suboptimal since the environment they provided was
not quite the same as the real container environment. See [1] for more
background.

Note that we directly invoke /bin/sh for `nixos-container root-login`
since setting the user's shell is quite complex. See [2] for a related
systemd issue.

[1]: systemd/systemd#825 (comment)
[2]: systemd/systemd#1395
  • Loading branch information
wlhlm authored and acowley committed Sep 29, 2016
1 parent 49b94ed commit aa7021e
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 23 deletions.
2 changes: 0 additions & 2 deletions pkgs/tools/virtualization/nixos-container/default.nix
Expand Up @@ -6,8 +6,6 @@ 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
Expand Down
23 changes: 2 additions & 21 deletions pkgs/tools/virtualization/nixos-container/nixos-container.pl
Expand Up @@ -8,9 +8,6 @@
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;

Expand Down Expand Up @@ -220,22 +217,6 @@ 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.
#
Expand Down Expand Up @@ -309,14 +290,14 @@ sub safeRemoveTree {
}

elsif ($action eq "root-login") {
runInContainer("@su@", "root", "-l");
exec("machinectl", "shell", $containerName, "/bin/sh", "-l");
}

elsif ($action eq "run") {
shift @ARGV; shift @ARGV;
# Escape command.
my $s = join(' ', map { s/'/'\\''/g; "'$_'" } @ARGV);
runInContainer("@su@", "root", "-l", "-c", "exec " . $s);
exec("machinectl", "--quiet", "shell", $containerName, "/bin/sh", "-l", "-c", $s);
}

elsif ($action eq "show-ip") {
Expand Down

0 comments on commit aa7021e

Please sign in to comment.