diff options
| -rw-r--r-- | CHANGELOG.md | 8 | ||||
| -rw-r--r-- | README.md | 15 | ||||
| -rw-r--r-- | flake.nix | 2 | ||||
| -rw-r--r-- | lib/with.nix | 13 | ||||
| -rw-r--r-- | pkgs/krops/default.nix | 98 | ||||
| -rw-r--r-- | pkgs/krops/populate.nix | 37 | ||||
| -rw-r--r-- | pkgs/krops/target.nix | 67 | ||||
| -rw-r--r-- | tests/default.nix | 3 | ||||
| -rw-r--r-- | tests/scenarios.nix | 44 |
9 files changed, 200 insertions, 87 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index ea60f0b..63f8018 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,14 @@ and krops' flake use the nixpkgs lib they get, instead of `<nixpkgs/lib>`. `lib/default.nix` stays for backwards compatibility, merging `<nixpkgs/lib>`, builtins, and `lib/with.nix`. +- krops works in pure evaluation, e.g. in flakes without `--impure`. + Target strings go to populate as they are, also from `writeDeploy`, + `writeCommand`, and `writeTest`, and `runShell`, which runs + `nixos-rebuild`, runs the new `populate shell`, which decides whether a + target is local when it runs. In pure evaluation, `mkTarget` leaves the + user and the host null, and target attribute sets leave whether they're + local to populate, which also refuses to copy flakes to targets using + sudo then. `runShell` returns shell code, also for remote targets. - A `passage` source's `identities_file` defaults to `~/.passage/identities` when populate runs, instead of during evaluation. @@ -102,8 +102,17 @@ taking nixpkgs' lib: } ``` -krops evaluates environment variables and `/etc/hostname`, which pure -evaluation doesn't allow, so deploy with `nix run --impure .#deploy`. +Deploy with `nix run .#deploy`. A target string goes to populate as it +is, which fills in what it leaves out, and decides whether the target is +local, when it runs, and so does `populate shell`, which runs +`nixos-rebuild`, and the commands of `writeCommand`, on targets. A target +attribute set gets `mkTarget`'s defaults, and whether it's local, during +evaluation, unless that's pure, as flakes evaluate by default, which can't +tell the user running krops, the machine's name, and whether a target is +local. Then `mkTarget` leaves the user and the host null, and populate +decides when it runs. It also refuses to copy flakes to targets using +sudo then, which krops otherwise refuses during evaluation, and +`writeDeploy` needs a target's host for a separate `buildTarget`. `pkgs.krops` provides the following functions. @@ -252,6 +261,8 @@ activating it. This basically makes the sources available on the target machine below `/var/src`, and executes `NIX_PATH=/var/src nix-build -A system '<nixpkgs/nixos>'`. +The target must be the machine krops runs on, which `writeTest` checks +during evaluation, or, if that's pure, before populating. ### `target` @@ -19,7 +19,7 @@ lib = forAllSystems (system: let pkgs = nixpkgs.legacyPackages.${system}; - krops = pkgs.callPackage ./pkgs/krops { inherit populate; }; + krops = pkgs.callPackage ./pkgs/krops { inherit populate populate-unwrapped; }; populate = pkgs.callPackage ./pkgs/krops/populate.nix { inherit populate-unwrapped; }; populate-unwrapped = pkgs.callPackage ./pkgs/populate {}; in { diff --git a/lib/with.nix b/lib/with.nix index 7305b7d..b3ff7fa 100644 --- a/lib/with.nix +++ b/lib/with.nix @@ -5,6 +5,10 @@ let populate.lib = import ../pkgs/populate/lib { inherit lib; }; + + # Whether evaluation is pure, which hides the environment and files + # outside the store. + pure = !(builtins ? currentSystem); in rec { @@ -30,19 +34,26 @@ rec { firstWord = s: lib.head (lib.match "^([^[:space:]]*).*" s); + # Whether target is the machine krops runs on, as the user running it. + # Pure evaluation can't tell, so krops leaves that to populate then. isLocalTarget = let origin = mkTarget ""; in target: target.user == origin.user && lib.elem target.host [origin.host "localhost"]; + # A target as krops' functions take it: an attribute set, with the parts + # the string s, [USER@][HOST][:PORT][PATH], leaves out defaulting to + # LOGNAME, the machine's name, and /var/src. Pure evaluation can't tell + # the first two, so they're null then, which populate fills in when it + # runs. s can also be an attribute set, which the defaults fill up. mkTarget = s: let parse = lib.match "(([^@]*)@)?(([^:/]+))?(:([^/]+))?(/.*)?" s; elemAt' = xs: i: if lib.length xs > i then lib.elemAt xs i else null; filterNull = lib.filterAttrs (n: v: v != null); in { user = lib.maybeEnv "LOGNAME" null; - host = lib.maybeEnv "HOSTNAME" (maybeHostName "localhost"); + host = if pure then null else lib.maybeEnv "HOSTNAME" (maybeHostName "localhost"); port = null; path = "/var/src"; sudo = false; diff --git a/pkgs/krops/default.nix b/pkgs/krops/default.nix index 248f033..b8924f5 100644 --- a/pkgs/krops/default.nix +++ b/pkgs/krops/default.nix @@ -1,7 +1,23 @@ -{ expect, lib, nix, openssh, populate, writers }: +{ expect, lib, nix, openssh, populate, populate-unwrapped, writers }: let klib = import ../../lib/with.nix { inherit lib; }; + targets = import ./target.nix { inherit lib; }; + + # What populate and populate shell get for target: a string as it is, so + # populate fills in what it leaves out when it runs, and an attribute set + # with mkTarget's defaults. + given = target: + if builtins.isString target then target else klib.mkTarget target; + + # Shell code running populate shell with options, for running the shell + # code command on target. + populateShell = options: target: command: /* sh */ '' + PATH=${lib.makeBinPath [ openssh ]}''${PATH:+:$PATH} \ + ${populate-unwrapped}/bin/populate shell ${lib.escapeShellArgs ( + options ++ targets.shellArgs (given target) command + )} + ''; in rec { @@ -12,13 +28,26 @@ rec { useNixOutputMonitor }: args: target: let + inherit (klib.mkTarget target) path; # The flake's directory in the target directory, and the name of the # NixOS configuration with its #, if any. flakeDir = lib.head (lib.splitString "#" flake); flakeAttr = lib.removePrefix flakeDir flake; in - runShell target { inherit allocateTTY; } - (withNixOutputMonitor target useNixOutputMonitor /* sh */ '' + runShell target { inherit allocateTTY; } ( + # Without ssh, which allocates the terminal on remote targets, unbuffer + # gives nixos-rebuild one. populate shell tells whether the target is + # local as $1, which nix-shell doesn't pass on, so it goes into the + # environment. + lib.optionalString allocateTTY /* sh */ '' + if test "$1" = local; then + krops_unbuffer=${expect}/bin/unbuffer + else + krops_unbuffer= + fi + export krops_unbuffer + '' + + withNixOutputMonitor target useNixOutputMonitor /* sh */ '' ${lib.optionalString (flake != null) /* sh */ '' ${klib.shell.requireFlakes "deploying a flake"} ${klib.shell.urlPath} @@ -26,7 +55,7 @@ rec { # deployed as path:, not just by its path, which Nix takes for the # enclosing Git work tree, if any. Nix refuses URLs with symlinks # on the way, which the target directory may be, or the source. - flake=$(readlink -f ${lib.escapeShellArg "${target.path}/${flakeDir}"}) + flake=$(readlink -f ${lib.escapeShellArg "${path}/${flakeDir}"}) if test -e "$flake"/.git; then if test -e "$flake"/.gitmodules; then flake=git+file:$(url_path "$flake")?submodules=1 @@ -37,10 +66,8 @@ rec { flake=path:$(url_path "$flake") fi ''} - NIX_PATH=${lib.escapeShellArg target.path} \ - ${lib.optionalString (allocateTTY && klib.isLocalTarget target) - # Without ssh, which allocates the terminal on remote targets. - "${expect}/bin/unbuffer"} \ + NIX_PATH=${lib.escapeShellArg path} \ + ${lib.optionalString allocateTTY "$krops_unbuffer"} \ nixos-rebuild ${lib.escapeShellArgs args} ${ if flake != null then ''--flake "$flake"${lib.escapeShellArg flakeAttr}'' @@ -51,27 +78,12 @@ rec { } ''); + # Shell code running the shell code command on target, reached like + # populate reaches it, with local or remote as $1, telling whether the + # target is local. runShell = target: { allocateTTY ? false - }: command: - let - command' = /* sh */ '' - ${lib.optionalString target.sudo "sudo"} \ - /bin/sh -c ${lib.escapeShellArg command} - ''; - in - if klib.isLocalTarget target - then command' - else - writers.writeDash "krops.${target.host}.${klib.firstWord command}" '' - exec ${openssh}/bin/ssh ${lib.escapeShellArgs (lib.flatten [ - (klib.mkUserPortSSHOpts target) - (if allocateTTY then "-t" else "-T") - target.extraOptions - target.host - command' - ])} - ''; + }: populateShell (lib.optional allocateTTY "--tty") target; withNixOutputMonitor = target: mode_: command: let mode = @@ -93,7 +105,7 @@ rec { (${command}) 2>&1 | nom ''; pessimistic = /* sh */ '' - NIX_PATH=${lib.escapeShellArg target.path} \ + NIX_PATH=${lib.escapeShellArg (klib.mkTarget target).path} \ nix-shell -p nix-output-monitor --run ${lib.escapeShellArg optimistic} ''; true = /* sh */ '' @@ -120,8 +132,8 @@ rec { in writers.writeDash name '' set -efu - ${populate { inherit backup force prune source; target = target'; }} - ${runShell target' { inherit allocateTTY; } (command target'.path)} + ${populate { inherit backup force prune source; target = given target; }} + ${runShell target { inherit allocateTTY; } (command target'.path)} ''; writeDeploy = name: { @@ -143,11 +155,15 @@ rec { then target' else klib.mkTarget buildTarget; target' = klib.mkTarget target; - # A host as nixos-rebuild takes it. Without a user, ssh decides. + # A host as nixos-rebuild takes it. Without a user, ssh decides. Pure + # evaluation can't tell the machine's name, which mkTarget defaults the + # host to. userHost = target: lib.optionalString (target.user != null && target.user != "") "${target.user}@" + - target.host; + (if target.host != null then target.host + else throw "krops: writeDeploy: a target with a separate buildTarget needs a host in pure evaluation"); + separateBuild = buildTarget' != target'; # The source's generated flake, if it draws inputs from other sources. flake' = let name = lib.head (lib.splitString "#" flake); @@ -163,20 +179,20 @@ rec { lib.traceIf (fast != null) "writeDeploy: it's now always fast, setting the `fast` attribute is deprecated and will be removed in future" ( writers.writeDash name '' set -efu - ${lib.optionalString (buildTarget' != target') - (populate { inherit backup force prune source; target = buildTarget'; })} - ${populate { inherit backup force prune source; target = target'; }} + ${lib.optionalString separateBuild + (populate { inherit backup force prune source; target = given buildTarget; })} + ${populate { inherit backup force prune source; target = given target; }} ${rebuild { flake = flake'; inherit allocateTTY useNixOutputMonitor; } ([ operation ] ++ lib.optionals crossDeploy [ "--no-build-nix" - ] ++ lib.optionals (buildTarget' != target') [ + ] ++ lib.optionals separateBuild [ "--build-host" (userHost buildTarget') "--target-host" (userHost target') - ] ++ lib.optionals (buildTarget' != target' && target'.sudo) [ + ] ++ lib.optionals (separateBuild && target'.sudo) [ # nixos-rebuild runs on the target itself via sudo otherwise. "--use-remote-sudo" - ]) buildTarget'} + ]) (if separateBuild then buildTarget else target)} '' ); @@ -190,10 +206,12 @@ rec { }: let target' = klib.mkTarget target; in - assert klib.isLocalTarget target'; + # Pure evaluation can't tell, so populate shell tells when it runs. + assert targets.pure || klib.isLocalTarget target'; writers.writeDash name '' set -efu - ${populate { inherit backup force prune source; target = target'; }} >&2 + ${populateShell [ "--local-only" ] target "true"} + ${populate { inherit backup force prune source; target = given target; }} >&2 NIX_PATH=${lib.escapeShellArg target'.path} \ ${nix}/bin/nix-build \ -A system \ diff --git a/pkgs/krops/populate.nix b/pkgs/krops/populate.nix index 83da9a6..0cc1606 100644 --- a/pkgs/krops/populate.nix +++ b/pkgs/krops/populate.nix @@ -7,8 +7,8 @@ }@args: let - klib = import ../../lib/with.nix { inherit lib; }; checks = import ./checks.nix { inherit lib; }; + targets = import ./target.nix { inherit lib; }; # Arguments populate doesn't use, which overrides written for krops 1 may # set. They come through ..., because callPackage would set named ones. @@ -18,41 +18,18 @@ let "rsync" "writers" "populate-unwrapped" ] ++ unused)); - # The parts of a target string, like mkTarget parses it, without its - # defaults, which populate fills in when it runs. - parseTarget = s: let - parts = builtins.match "(([^@]*)@)?(([^:/]+))?(:([^/]+))?(/.*)?" s; - in - if parts == null then throw "krops: invalid target ${builtins.toJSON s}" - else { host = builtins.elemAt parts 3; path = builtins.elemAt parts 6; }; - populate = { backup ? false, force ? false, prune ? false, source, target }: let - # A target string goes to populate as it is, so populate decides what - # it leaves out when it runs. An attribute set, as mkTarget returns - # it, goes part by part, with whether it's local decided now, like the - # other functions of krops do. - parsed = parseTarget target; - path = if builtins.isString target then (if parsed.path != null then parsed.path else "/var/src") else target.path; - host = if builtins.isString target then (if parsed.host != null then parsed.host else "localhost") else target.host; - targetArgs = - if builtins.isString target then [ target ] - else [ - "--user" (if target.user or null == null then "" else target.user) - "--host" target.host - "--path" target.path - ] ++ lib.optionals (target.port or null != null) [ - "--port" (toString target.port) - ] ++ lib.optional (target.sudo or false) "--sudo" - ++ builtins.concatMap (arg: [ "--ssh-arg" arg ]) (lib.flatten (target.extraOptions or [])) - ++ [ (if klib.isLocalTarget target then "--local" else "--remote") ]; + path = (targets.parts target).path; in assert checks.checkTargetPath path; assert builtins.all checks.checkSourceName (builtins.attrNames source); assert checks.checkInputs source; - assert builtins.isString target || checks.checkCopyingWithSudo target source; - writers.writeDash "populate.${host}" /* sh */ '' + # Populate refuses that as well, when it runs. + assert builtins.isString target || targets.pure || + checks.checkCopyingWithSudo target source; + writers.writeDash "populate.${targets.name target}" /* sh */ '' set -efu echo + "$0" >&2 PATH=${lib.makeBinPath [ @@ -67,7 +44,7 @@ let lib.optional backup "--backup" ++ lib.optional force "--force" ++ lib.optional prune "--prune" - )} /dev/fd/3 ${lib.escapeShellArgs targetArgs} 3<<'EOF' + )} /dev/fd/3 ${lib.escapeShellArgs (targets.populateArgs target)} 3<<'EOF' ${builtins.toJSON source} EOF ''; diff --git a/pkgs/krops/target.nix b/pkgs/krops/target.nix new file mode 100644 index 0000000..9cb7a31 --- /dev/null +++ b/pkgs/krops/target.nix @@ -0,0 +1,67 @@ +# Targets as krops' functions take them: strings, which go to populate as +# they are, so it fills in what they leave out when it runs, and attribute +# sets, as mkTarget returns them, which go part by part, with whether the +# target is local decided during evaluation, unless that's pure. +{ lib }: + +let + klib = import ../../lib/with.nix { inherit lib; }; +in + +rec { + # Whether evaluation is pure, which can't tell mkTarget's defaults for + # the user and the host, nor whether a target is local. + pure = !(builtins ? currentSystem); + + # The parts of target, a string parsed like mkTarget parses it, but with + # only the path defaulting, to /var/src, or an attribute set. + parts = target: + if builtins.isString target then let + parsed = builtins.match "(([^@]*)@)?(([^:/]+))?(:([^/]+))?(/.*)?" target; + part = builtins.elemAt parsed; + in + if parsed == null then + throw "krops: invalid target ${builtins.toJSON target}" + else { + user = part 1; + host = part 3; + port = part 5; + path = if part 6 == null then "/var/src" else part 6; + sudo = false; + extraOptions = []; + } + else target; + + # populate's or populate shell's options for an attribute set target, + # the first with the path, if withPath. Pure evaluation leaves out the + # user and the host if they're null, and whether the target is local, + # which populate decides. + options = withPath: target: + lib.optionals (!pure || target.user or null != null) [ + "--user" (if target.user or null == null then "" else target.user) + ] ++ lib.optionals (!pure || target.host or null != null) [ + "--host" target.host + ] ++ lib.optionals withPath [ + "--path" target.path + ] ++ lib.optionals (target.port or null != null) [ + "--port" (toString target.port) + ] ++ lib.optional (target.sudo or false) "--sudo" + ++ builtins.concatMap (arg: [ "--ssh-arg" arg ]) + (lib.flatten (target.extraOptions or [])) + ++ lib.optional (!pure) + (if klib.isLocalTarget target then "--local" else "--remote"); + + # populate's arguments for target, after the sources. + populateArgs = target: + if builtins.isString target then [ target ] + else options true target; + + # populate shell's arguments for running script on target. + shellArgs = target: script: + if builtins.isString target then [ "--" target script ] + else options false target ++ [ "--" "" script ]; + + # The host of target, for naming scripts, or localhost if it has none. + name = target: let host = (parts target).host; in + if host == null then "localhost" else host; +} diff --git a/tests/default.nix b/tests/default.nix index fa82e3a..08f95a6 100644 --- a/tests/default.nix +++ b/tests/default.nix @@ -70,7 +70,8 @@ let # Names of the scenarios of the smoke test, besides populate's. smokeNames = import (populateTests + "/smoke.nix") ++ [ - "deploy-local-buildTarget0-etcFlake0-flakefile" + "deploy-local-buildTarget0-etcFlake0-flakefile-targetString0" + "deploy-remote-buildTarget0-etcFlake0-flakenone-targetString1" "deploy-sudo-allocateTTY" ]; diff --git a/tests/scenarios.nix b/tests/scenarios.nix index e61d25b..0e90284 100644 --- a/tests/scenarios.nix +++ b/tests/scenarios.nix @@ -5,10 +5,17 @@ { targets, ... }@args: let - inherit (args) lib gitHead gitUrl; - inherit (lib) concatStringsSep optional optionalAttrs optionals optionalString; + inherit (args) lib gitHead gitUrl remoteHost; + inherit (lib) concatMap concatStringsSep optional optionalAttrs optionals optionalString; inherit (import ../pkgs/populate/tests/builder.nix (removeAttrs args [ "targets" ])) alt drawInputs matrix scenario targetKinds twice; + + # The target of a kind for a path, as a string, which can't say to use + # sudo. + targetString = targetKind: path: { + local = path; + remote = "root@${remoteHost}${path}"; + }.${targetKind}; in { @@ -16,11 +23,13 @@ in # writeDeploy's arguments to nixos-rebuild, which a stand-in records. # flake is what gets deployed: nothing, or a flake from a file, git, or # flake source, or one whose inputs get drawn from a source, by rewriting - # its lock file or through a generated flake. + # its lock file or through a generated flake. targetString gives the + # target as a string, which populate and populate shell get as it is. deploy = matrix "deploy" { flake = [ "none" "file" "git" "source" "rewrite" "generated" ]; etcFlake = [ false true ]; buildTarget = [ false true ]; + targetString = [ false true ]; } (flags: ctx: let target = targets.${ctx.targetKind} ctx.path; buildTarget = targets.local "${ctx.path}-build"; @@ -42,11 +51,15 @@ in if flags.flake == "generated" then ".populate/flakes/x" else "x"; scheme = if flags.flake == "git" then "git+file" else "path"; in - # The local target can't have another build target. - if flags.buildTarget && ctx.targetKind == "local" then null else { + # The local target can't have another build target, and a string can't + # say to use sudo. + if flags.buildTarget && ctx.targetKind == "local" || + flags.targetString && ctx.targetKind == "sudo" then null else { node = if flags.buildTarget then "deployer" else null; - # /etc/nixos/flake.nix only matters if no flake gets deployed. - exhaustive = flags.etcFlake && flags.flake != "none"; + # /etc/nixos/flake.nix only matters if no flake gets deployed, and + # how the target is given not for what gets deployed. + exhaustive = flags.etcFlake && flags.flake != "none" || + flags.targetString && flags.flake != "none"; # Each scenario creates or removes /etc/nixos/flake.nix. prepare = '' rm -f /tmp/nixos-rebuild.log @@ -74,6 +87,8 @@ in flake = if flags.flake == "none" then null else "x"; } // optionalAttrs flags.buildTarget { inherit buildTarget; + } // optionalAttrs flags.targetString { + target = targetString ctx.targetKind ctx.path; }; check = '' expect_eq user "$(sed -n 1p /tmp/nixos-rebuild.log)" 0 @@ -91,16 +106,21 @@ in # writeDeploy with allocateTTY: nixos-rebuild's output is a terminal on # the local target. ssh allocates one on remote targets only if its own - # input is a terminal, which the tests' isn't. - ++ map (targetKind: scenario { - name = "deploy-${targetKind}-allocateTTY"; + # input is a terminal, which the tests' isn't. Whether the target is + # local, populate shell decides, also for a target string. + ++ concatMap (targetKind: map (string: scenario (rec { + name = "deploy-${targetKind}${optionalString string "-string"}-allocateTTY"; inherit targetKind; prepare = '' rm -f /tmp/nixos-rebuild.log /etc/nixos/flake.nix ''; phases = [{ sources.x.file = "/fixtures/alt"; - deploy.allocateTTY = true; + deploy = { + allocateTTY = true; + } // optionalAttrs string { + target = targetString targetKind "/var/krops/${name}"; + }; check = '' expect_eq arguments "$(sed -n 3p /tmp/nixos-rebuild.log)" switch expect_eq terminal "$(sed -n 4p /tmp/nixos-rebuild.log)" ${ @@ -108,6 +128,6 @@ in } ''; }]; - }) targetKinds; + })) (if targetKind == "sudo" then [ false ] else [ false true ])) targetKinds; } |
