diff --git a/AGENTS.md b/AGENTS.md index 3abdfa0..b8a1016 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,9 +58,10 @@ Common ones: (`deploy --boot .#`) — the box keeps running its current generation until it reboots. Use this when a live `switch` would break connectivity mid-change (e.g. a router's WAN VLAN rework), then reboot to cut over. -- `ssh-machine [cmd]` — SSH to a NixOS system or home-manager config by name. Resolves the - target and ssh options (identity, port) from its deploy-rs node, so it needs `my.deploy.enable` - (same gate as `deploy`). Connection settings for all nodes are cached together and invalidated +- `ssh-machine [cmd]` — connect to a box, home-manager config or NixOS container by name. + Uses SSH settings from the deploy-rs node, so the box or container host needs `my.deploy.enable`. + For containers use the instance name or `.container-` to get a root shell through + the host. Connection settings for all nodes are cached together and invalidated by checkout changes (the jj working copy, else tracked Git changes); use `ssh-machine --refresh` to force a refresh (see `docs/deployment.md#ssh-machine`). Boxes default to the `fish` login shell, so pipe multi-statement remote diff --git a/deploy-rs.nix b/deploy-rs.nix index d174748..1cd8907 100644 --- a/deploy-rs.nix +++ b/deploy-rs.nix @@ -27,6 +27,11 @@ in internal = true; description = "Rendered deploy-rs configuration."; }; + sshConnections = mkOption { + type = attrsOf unspecified; + internal = true; + description = "SSH connection settings and container names for ssh-machine."; + }; }; config = { @@ -53,6 +58,20 @@ in # Filter out null values so deploy merges overriding options correctly rendered = lib.my.deploy-rs.filterOpts cfg.deploy; + + sshConnections = mapAttrs (name: node: + let + system = systems.${name}.configuration.config or null; + hostnames = if system == null then [ ] else system.my.deploy.sshHostnames; + instances = if system == null then { } else system.my.containers.instances; + in + { + inherit (node) sshUser; + sshOpts = cfg.rendered.sshOpts ++ node.sshOpts; + hostnames = if hostnames == [ ] then [ node.hostname ] else hostnames; + containers = attrNames instances; + sudo = node.sudo or (cfg.rendered.sudo or "sudo -u"); + }) cfg.rendered.nodes; }; }; } diff --git a/devshell/commands.nix b/devshell/commands.nix index 988fc85..6bc944c 100644 --- a/devshell/commands.nix +++ b/devshell/commands.nix @@ -4,8 +4,8 @@ let devKey = ".keys/dev.key"; sshMachine = pkgs.writeShellApplication { name = "ssh-machine"; - runtimeInputs = with pkgs; [ coreutils git jujutsu jq openssh ]; - text = builtins.readFile ./ssh-machine.sh; + runtimeInputs = with pkgs; [ git jujutsu netcat-openbsd openssh ]; + text = ''exec ${pkgs.python3.interpreter} ${./ssh-machine.py} "$@"''; }; in { @@ -56,7 +56,7 @@ in { name = "ssh-machine"; category = "utilities"; - help = "SSH to a machine by NixOS system or home-manager config name"; + help = "Connect to a box, home-manager config or NixOS container by name"; command = ''exec ${sshMachine}/bin/ssh-machine "$@"''; } { diff --git a/devshell/ssh-machine.py b/devshell/ssh-machine.py new file mode 100644 index 0000000..57614b8 --- /dev/null +++ b/devshell/ssh-machine.py @@ -0,0 +1,171 @@ +import hashlib +import json +import os +import shlex +import subprocess +import sys +import tempfile +from pathlib import Path + + +CACHE = Path(".cache/ssh-machine/connections.json") +CACHE_VERSION = 2 + + +def fingerprint(): + # The jj working-copy commit covers the snapshotted tree, even in secondary workspaces. + if subprocess.run(["jj", "root"], capture_output=True).returncode == 0: + return subprocess.check_output( + ["jj", "log", "--no-pager", "--color", "never", "--no-graph", "-r", "@", "-T", "commit_id"], + text=True, + ).strip() + + diff = ["git", "diff", "--no-ext-diff", "--no-textconv", "--binary"] + digest = hashlib.sha256() + for command in (["git", "rev-parse", "HEAD"], [*diff, "HEAD", "--"], [*diff, "--cached", "--"]): + digest.update(subprocess.check_output(command)) + return digest.hexdigest() + + +def load_connections(refresh): + key = fingerprint() + if not refresh: + try: + cached = json.loads(CACHE.read_text(encoding="utf-8")) + except (OSError, ValueError): + cached = {} + if ( + isinstance(cached, dict) + and cached.get("fingerprint") == key + and cached.get("version") == CACHE_VERSION + and isinstance(cached.get("nodes"), dict) + ): + return cached["nodes"] + + print("Refreshing ssh-machine connection cache…", file=sys.stderr) + nodes = json.loads(subprocess.check_output( + ["nix", "eval", "--json", ".#nixfiles.config.deploy-rs.sshConnections"] + )) + if fingerprint() != key: + sys.exit("Checkout changed during evaluation; retry ssh-machine.") + + CACHE.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile( + mode="w", encoding="utf-8", dir=CACHE.parent, prefix=".connections.", delete=False + ) as temporary: + try: + json.dump({"fingerprint": key, "version": CACHE_VERSION, "nodes": nodes}, temporary) + temporary.flush() + os.replace(temporary.name, CACHE) + finally: + Path(temporary.name).unlink(missing_ok=True) + + return nodes + + +def resolve_target(nodes, name): + # deploy-rs mangles home configuration names containing @. + node_name = name.replace("@", "-at-") + if node_name in nodes: + return nodes[node_name], None + + matches = {} + for host, node in nodes.items(): + for container in node["containers"]: + qualified = f"{host}.container-{container}" + if name in (container, qualified): + matches[qualified] = (node, container) + + if len(matches) == 1: + return next(iter(matches.values())) + if matches: + sys.exit(f"Ambiguous container name: {', '.join(sorted(matches))}") + sys.exit(f"Unknown deploy node or container: {name}") + + +def ssh_port(node, hostname): + config = subprocess.run( + ["ssh", "-G", *node["sshOpts"], f"{node['sshUser']}@{hostname}"], + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, + ) + if config.returncode == 0: + for line in config.stdout.splitlines(): + key, _, value = line.partition(" ") + if key == "port": + return value + return None + + +def select_hostname(node): + # Check preferred addresses before starting SSH so a remote command only runs once. + *preferred, fallback = node["hostnames"] + for hostname in preferred: + port = ssh_port(node, hostname) + if port is None: + continue + try: + probe = subprocess.run( + ["nc", "-z", "--", hostname, port], timeout=2, + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + except subprocess.TimeoutExpired: + continue + if probe.returncode == 0: + return hostname + return fallback + + +def container_command(node, container, command, tty): + args = [ + "root", "systemd-run", "--quiet", "--wait", "--collect", + "--expand-environment=no", "--working-directory=~", + "--pty" if tty else "--pipe", + f"--machine={container}", "--", "/run/current-system/sw/bin/bash", "-l", + ] + if command: + # SSH joins command arguments with spaces before passing them to the remote shell. + args += ["-c", " ".join(command)] + return f"{node['sudo']} {shlex.join(args)}" + + +def main(args): + refresh = args[:1] == ["--refresh"] + if refresh: + args = args[1:] + if args[:1] == ["--help"] or (not refresh and not args): + print("Usage: ssh-machine [--refresh] [cmd ...]") + print(" ssh-machine [--refresh] .container- [cmd ...]") + print(" ssh-machine --refresh") + return + + # Resolve deploy's relative identity path from the checkout root. + project_root = os.environ.get("PRJ_ROOT") + if not project_root: + sys.exit("ssh-machine: PRJ_ROOT is unset. Enter the devshell first.") + os.chdir(project_root) + nodes = load_connections(refresh) + if not args: + return + + name, *command = args + node, container = resolve_target(nodes, name) + hostname = select_hostname(node) + destination = f"{node['sshUser']}@{hostname}" + + ssh = ["ssh", *node["sshOpts"]] + if container is not None: + tty = not command and sys.stdin.isatty() + if tty: + ssh.append("-t") + command = [container_command(node, container, command, tty)] + + os.execvp("ssh", [*ssh, destination, *command]) + + +if __name__ == "__main__": + try: + main(sys.argv[1:]) + except subprocess.CalledProcessError as error: + sys.exit(error.returncode) + except (OSError, ValueError) as error: + sys.exit(f"ssh-machine: {error}") diff --git a/devshell/ssh-machine.sh b/devshell/ssh-machine.sh deleted file mode 100644 index f6ec369..0000000 --- a/devshell/ssh-machine.sh +++ /dev/null @@ -1,80 +0,0 @@ -set -euo pipefail - -refresh=false - -if [[ ${1:-} == --refresh ]]; then - refresh=true - shift -fi - -if [[ $# == 0 && $refresh == false ]] || [[ ${1:-} == --help ]]; then - echo 'Usage: ssh-machine [--refresh] [cmd ...]' - echo ' ssh-machine --refresh' - exit 0 -fi - -# Resolve deploy's relative identity path from the checkout root. -cd "$PRJ_ROOT" - -cache_dir=.cache/ssh-machine -cache=$cache_dir/connections.json - -fingerprint() { - # A jj working-copy commit's ID covers its whole snapshotted tree, so it changes with any - # working-copy edit. This also works in secondary workspaces, which have no Git checkout. - if jj root >/dev/null 2>&1; then - jj log --no-pager --color never --no-graph -r @ -T 'commit_id' - else - { - git rev-parse HEAD && - git diff --no-ext-diff --no-textconv --binary HEAD -- && - git diff --no-ext-diff --no-textconv --binary --cached -- - } | sha256sum | cut -d ' ' -f 1 - fi -} - -key=$(fingerprint) - -if [[ $refresh == true ]] || ! jq -e --arg key "$key" \ - '.fingerprint == $key and (.nodes | type == "object")' "$cache" >/dev/null 2>&1; then - mkdir -p "$cache_dir" - tmp=$(mktemp "$cache_dir/.connections.XXXXXXXX") - trap 'rm -f "$tmp"' EXIT - - echo 'Refreshing ssh-machine connection cache…' >&2 - - # Interpolation here belongs to Nix, not the shell. - # shellcheck disable=SC2016 - nix eval --json .#deploy --apply ' - d: builtins.mapAttrs (_: n: - d.sshOpts ++ n.sshOpts ++ [ "${n.sshUser}@${n.hostname}" ] - ) d.nodes - ' > "$tmp" - - if [[ $(fingerprint) != "$key" ]]; then - echo 'Checkout changed during evaluation; retry ssh-machine.' >&2 - exit 1 - fi - - payload=$(jq -c --arg key "$key" '{fingerprint: $key, nodes: .}' "$tmp") - printf '%s\n' "$payload" > "$tmp" - mv -f "$tmp" "$cache" - trap - EXIT -fi - -[[ $# -gt 0 ]] || exit 0 - -name=$1 -shift - -# deploy-rs mangles home configuration names containing @. -node=${name//@/-at-} - -args=$(jq -ce --arg node "$node" ' - .nodes | if has($node) then .[$node] - else error("Unknown deploy node: " + $node) end -' "$cache") - -mapfile -d '' -t ssh_args < <(jq -j '.[] | ., "\u0000"' <<< "$args") - -exec ssh "${ssh_args[@]}" "$@" diff --git a/docs/deployment.md b/docs/deployment.md index 373497b..ea308a2 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -57,10 +57,19 @@ Generated profiles deploy in this order: #### `ssh-machine` -`ssh-machine [cmd]` resolves `user@host` and the merged global/node `sshOpts` from -`.#deploy`, using the same `my.deploy.enable` gate and `@` → `-at-` mangling as `deploy`, then runs -`ssh`. Connection settings for all nodes are cached together in `.cache/ssh-machine/`; -normal connections read the cache without running Nix. A fingerprint of the checkout +`ssh-machine [cmd]` connects using the deploy-rs node's SSH user and merged global and +node `sshOpts`. Box and home targets use the same `my.deploy.enable` gate and `@` → `-at-` +mangling as `deploy`. If a box sets `my.deploy.sshHostnames`, the command checks the +addresses in order for a reachable SSH port and uses the last address if the earlier checks fail. + +For NixOS containers, use `ssh-machine middleman` or `ssh-machine shill.container-middleman`. +The qualified name selects the host when multiple containers share a name or a deploy node has +the same name. The command connects to the host's deploy node and uses `systemd-run` to open a +root Bash shell in the container or run the supplied command there. Stdin and the command's +exit status are available to the caller. + +Connection settings and container names are cached together in `.cache/ssh-machine/`. +Normal connections read the cache without running Nix. A fingerprint of the checkout automatically invalidates it. In a Jujutsu workspace (including secondary workspaces without a Git checkout) it is the working-copy commit ID, so any snapshotted change counts, including new files that are not ignored. In a Git-only checkout it is HEAD plus staged/unstaged tracked @@ -102,7 +111,7 @@ command with no arguments for its help. From | `home-switch [args]` | `home-manager switch --flake .`. | | `deploy [args]` | `deploy-rs --skip-checks` (wrapper package in `devshell/default.nix`). | | `deploy --targets .# .#` | Deploys several nodes in one invocation. | -| `ssh-machine [cmd]` | SSH to a system or home by name, resolving target/options from its deploy-rs node (see above). | +| `ssh-machine [cmd]` | Connect to a box, home-manager config or NixOS container using deploy-rs SSH settings. | | `run-vm ` | Boots a system as a dev VM: installs `.keys/dev.key` into a temp `xchg/`, then `nix run`s `config.my.buildAs.devVM`. | | `build-iso ` | Builds `config.my.buildAs.iso`. | | `build-kexec ` | Builds `config.my.buildAs.kexecTree`. | diff --git a/docs/mobile/tower.md b/docs/mobile/tower.md index b911581..76d26df 100644 --- a/docs/mobile/tower.md +++ b/docs/mobile/tower.md @@ -42,6 +42,8 @@ over Tailscale. - NetworkManager (`wpa_supplicant` backend) with `systemd-resolved`; networkd `wait-online` is disabled. The Wi-Fi interface is renamed to `wifi` by MAC. +- `ssh-machine tower` uses `tower.dyn.h.nul.ie` when its SSH port is reachable and + `tower.ts.nul.ie` over Tailscale otherwise. - Steam and Wireshark enabled; `fstrim`, LVM thin provisioning. - `nix.gc.automatic = false` — GC is run manually on the laptop. diff --git a/nixos/boxes/tower/default.nix b/nixos/boxes/tower/default.nix index cf8cf22..71fb2eb 100644 --- a/nixos/boxes/tower/default.nix +++ b/nixos/boxes/tower/default.nix @@ -196,6 +196,11 @@ }; }; + deploy.sshHostnames = with lib.my.c; [ + "tower.dyn.${home.domain}" + "tower.ts.${pubDomain}" + ]; + #deploy.generate.system.mode = "boot"; secrets = { key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOU+UxJh8PZoiXV+0CRumv9Xsk6Fks4YMYRZcThmaJkB"; diff --git a/nixos/modules/deploy-rs.nix b/nixos/modules/deploy-rs.nix index ffbed59..14aafac 100644 --- a/nixos/modules/deploy-rs.nix +++ b/nixos/modules/deploy-rs.nix @@ -100,6 +100,8 @@ in enable = mkBoolOpt' true "Whether to expose deploy-rs configuration for this system."; inherit (lib.my.deploy-rs) node; + sshHostnames = mkOpt' (listOf str) [ ] + "Addresses for ssh-machine in order of preference. Defaults to the deploy-rs hostname."; generate = { system = {