nixos/nixos-container: ensure that the state-dir is cleaned up if a build fails

gstqt5
Maximilian Bosch 2020-02-10 02:21:24 +01:00
parent c6fa3c201c
commit 93943acbc5
No known key found for this signature in database
GPG Key ID: 091DBF4D1FC46B8E
2 changed files with 34 additions and 7 deletions

View File

@ -46,6 +46,15 @@ import ./make-test-python.nix ({ pkgs, ...} : {
};
}
'';
brokenCfg = pkgs.writeText "broken.nix" ''
{
assertions = [
{ assertion = false;
message = "I never evaluate";
}
];
}
'';
in ''
with subtest("Make sure we have a NixOS tree (required by nixos-container create)"):
machine.succeed("PAGER=cat nix-env -qa -A nixos.hello >&2")
@ -130,5 +139,11 @@ import ./make-test-python.nix ({ pkgs, ...} : {
with subtest("Ensure that the container path is gone"):
print(machine.succeed("ls -lsa /var/lib/containers"))
machine.succeed(f"test ! -e /var/lib/containers/{id1}")
with subtest("Ensure that a failed container creation doesn'leave any state"):
machine.fail(
"nixos-container create b0rk --config-file ${brokenCfg}"
)
machine.succeed(f"test ! -e /var/lib/containers/b0rk")
'';
})

View File

@ -149,6 +149,16 @@ sub buildFlake {
unlink("$systemPath.tmp");
}
sub clearContainerState {
my ($profileDir, $gcRootsDir, $root, $configFile) = @_;
safeRemoveTree($profileDir) if -e $profileDir;
safeRemoveTree($gcRootsDir) if -e $gcRootsDir;
system("chattr", "-i", "$root/var/empty") if -e "$root/var/empty";
safeRemoveTree($root) if -e $root;
unlink($configFile) or die;
}
if ($action eq "create") {
# Acquire an exclusive lock to prevent races with other
# invocations of nixos-container create.
@ -226,7 +236,10 @@ if ($action eq "create") {
if (defined $systemPath) {
system("nix-env", "-p", "$profileDir/system", "--set", $systemPath) == 0
or die "$0: failed to set initial container configuration\n";
or do {
clearContainerState($profileDir, "$profileDir/$containerName", $root, $confFile);
die "$0: failed to set initial container configuration\n";
};
} else {
mkpath("$root/etc/nixos", 0, 0755);
@ -237,7 +250,10 @@ if ($action eq "create") {
system("nix-env", "-p", "$profileDir/system",
"-I", "nixos-config=$nixosConfigFile", "-f", "$nixenvF",
"--set", "-A", "system") == 0
or die "$0: failed to build initial container configuration\n";
or do {
clearContainerState($profileDir, "$profileDir/$containerName", $root, $confFile);
die "$0: failed to build initial container configuration\n"
};
}
print "$containerName\n" if $ensureUniqueName;
@ -331,11 +347,7 @@ if ($action eq "destroy") {
terminateContainer if (isContainerRunning);
safeRemoveTree($profileDir) if -e $profileDir;
safeRemoveTree($gcRootsDir) if -e $gcRootsDir;
system("chattr", "-i", "$root/var/empty") if -e "$root/var/empty";
safeRemoveTree($root) if -e $root;
unlink($confFile) or die;
clearContainerState($profileDir, $gcRootsDir, $root, $confFile);
}
elsif ($action eq "restart") {