"""Builds or runs a command on a remote Linux machine, in a copy there of this working copy with its changes. python -u Scripts/remotebuild.py build --project Vellum.UnitTests --quiet-summary python -u Scripts/remotebuild.py run -- dotnet Junk/Vellum.UnitTests/Release/Vellum.UnitTests.dll --times python -u Scripts/remotebuild.py sync Each working copy gets a copy of its own on the machine, named for its path, so sessions in different workspaces never share one. Before each command the copy is brought to this working copy's revisions and given its pending changes: modified and added files are copied over, and deleted ones deleted. Those svn keeps with native line endings arrive with LF, as a checkout there would hold them. Unversioned files are not copied, so `svn add` a new file first. The previous sync is undone first, so the copy always matches this working copy exactly. The machine is described by ~/.electricroot-remote.json, whose keys and defaults are CONFIG_DEFAULTS. The command runs under systemd-inhibit, so the machine can't sleep partway through, and its exit code is this script's. """ import argparse import io import json import os import re import shlex import socket import subprocess import sys import tarfile import threading import time import xml.etree.ElementTree as ElementTree REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) CONFIG_PATH = os.path.join(os.path.expanduser("~"), ".electricroot-remote.json") CONFIG_DEFAULTS = { # An ssh host, usually an alias from ~/.ssh/config that names the user and key. "host": "desktop", # The machine's MAC address, to wake it with a magic packet when ssh can't reach it. None leaves it asleep. "wake_mac": None, "wake_broadcast": "255.255.255.255", "wake_timeout_seconds": 90, # A checkout on the machine that a new copy starts from, so it needn't be checked out from scratch. "seed": "~/ElectricRoot", # Where the copies live, one folder per working copy. "copies": "~/remote-builds", # Shell run before each command, such as one that puts the right .NET SDK on PATH. "environment": "", } # The files the last sync added, which reverting leaves behind, so the next sync deletes them. SYNC_MANIFEST = ".remote-sync-added" ANSI_ESCAPE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]") def load_config(path=CONFIG_PATH): """The machine's settings: CONFIG_DEFAULTS, overridden by whatever the config file at `path` sets.""" returnMe = dict(CONFIG_DEFAULTS) if os.path.exists(path): with open(path, encoding="utf-8") as file: settings = json.load(file) unknown = sorted(set(settings) - set(CONFIG_DEFAULTS)) if unknown: raise SystemExit("{} sets {}, which aren't settings. The settings are {}.".format( path, ", ".join(unknown), ", ".join(sorted(CONFIG_DEFAULTS)))) returnMe.update(settings) return returnMe def copy_name(repo_root): """The name of a working copy's copy on the machine, built from its path, such as ElectricRoot-Scratch-09.""" _, path = os.path.splitdrive(os.path.abspath(repo_root)) parts = [part for part in re.split(r"[\\/]+", path) if part] return re.sub(r"[^A-Za-z0-9._-]", "_", "-".join(parts)) def remote_path(path): """A path for a remote shell, with a leading ~ spelled $HOME so it still expands inside double quotes.""" if path == "~" or path.startswith("~/"): return "$HOME" + path[1:] return path def parse_externals(property_text): """The directories an svn:externals property names, in either the old "dir URL" or the new "URL dir" order.""" returnMe = [] for line in property_text.splitlines(): words = [word for word in line.split() if not word.startswith("-r")] if len(words) < 2 or line.lstrip().startswith("#"): continue urls = [word for word in words if "://" in word or word.startswith("^/")] directories = [word for word in words if word not in urls and not word.isdigit()] if urls and directories: returnMe.append(directories[-1]) return returnMe def parse_status(text): """Splits `svn status` output into the paths to copy and the paths to delete, each relative and with / slashes. Copying covers modified, added and replaced items, deleting covers deleted and missing ones. Everything else, such as unversioned files, externals and changelist headings, is left out. """ to_copy = [] to_delete = [] for line in text.splitlines(): if len(line) < 9 or line[7] != " " or line.startswith("---"): continue path = line[8:].strip().replace("\\", "/") if line[0] in "MAR": to_copy.append((line[0], path)) elif line[0] in "D!": to_delete.append(path) return to_copy, to_delete def svn_revision(path): """The revision a working copy directory is checked out at.""" xml = subprocess.run(["svn", "info", "--xml", path], capture_output=True, text=True, check=True).stdout return ElementTree.fromstring(xml).find("entry").get("revision") def local_state(repo_root): """What a copy needs to match `repo_root`: its revision, each external's, and its pending changes. Returns: (root revision, {external: revision}, [(status, path to copy)], [path to delete]) """ externals_text = subprocess.run(["svn", "propget", "svn:externals", repo_root], capture_output=True, text=True, check=True).stdout externals = [external for external in parse_externals(externals_text) if os.path.isdir(os.path.join(repo_root, external))] external_revisions = {external: svn_revision(os.path.join(repo_root, external)) for external in externals} status = subprocess.run(["svn", "status"], cwd=repo_root, capture_output=True, text=True, check=True).stdout to_copy, to_delete = parse_status(status) # A directory's files appear as entries of their own, so only files need copying. to_copy = [(code, path) for code, path in to_copy if os.path.isfile(os.path.join(repo_root, path))] return svn_revision(repo_root), external_revisions, to_copy, to_delete def parse_native_eol_paths(propget_text): """The paths `svn propget svn:eol-style` lists as native, relative and with / slashes.""" returnMe = set() for line in propget_text.splitlines(): path, separator, style = line.rpartition(" - ") if separator and style.strip() == "native": returnMe.add(path.strip().replace("\\", "/")) return returnMe def native_eol_paths(repo_root, paths): """Which of `paths` svn keeps with native line endings, so a checkout on the machine holds them with LF.""" if not paths: return set() # A path with no eol-style makes svn warn and exit nonzero, though it still lists the rest. output = subprocess.run(["svn", "propget", "svn:eol-style"] + list(paths), cwd=repo_root, capture_output=True, text=True).stdout return parse_native_eol_paths(output) def tar_of(repo_root, paths, lf_paths=()): """A gzipped tar of the files at `paths`, relative to `repo_root`, with those in `lf_paths` given LF endings.""" buffer = io.BytesIO() with tarfile.open(fileobj=buffer, mode="w:gz") as archive: for path in paths: source = os.path.join(repo_root, path) if path not in lf_paths: archive.add(source, arcname=path) continue with open(source, "rb") as file: data = file.read().replace(b"\r\n", b"\n") info = archive.gettarinfo(source, arcname=path) info.size = len(data) archive.addfile(info, io.BytesIO(data)) return buffer.getvalue() def sync_script(config, name, root_revision, external_revisions, to_copy, to_delete): """The shell that makes the copy `name` match a working copy, reading the changed files as a tar on stdin.""" copies = remote_path(config["copies"]) seed = remote_path(config["seed"]) quiet_svn = "svn --non-interactive -q" lines = [ "set -e", 'copy="{}/{}"'.format(copies, name), 'if [ ! -d "$copy/.svn" ]; then', ' mkdir -p "{}"'.format(copies), ' echo "Making $copy from {}..."'.format(config["seed"]), ' cp -a "{}" "$copy"'.format(seed), "fi", 'cd "$copy"', # Reverting leaves files the last sync added in place, since they were never added to svn here. "if [ -f {0} ]; then while IFS= read -r path; do rm -f -- \"$path\"; done < {0}; fi".format(SYNC_MANIFEST), "{} revert -R .".format(quiet_svn), ] for external in sorted(external_revisions): lines.append("{} revert -R {}".format(quiet_svn, shlex.quote(external))) # Asking the server costs most of a sync, so a directory already at its revision is left alone. targets = [(".", root_revision, "--ignore-externals ")] + [ (shlex.quote(external), revision, "") for external, revision in sorted(external_revisions.items())] for target, revision, options in targets: lines.append('[ "$(svn info --show-item revision {0})" = "{1}" ] || {2} update {3}-r {1} {0}'.format( target, revision, quiet_svn, options)) # Stamped with the time they land, not the time they were edited, so a build there always sees them as changed. lines.append("tar -xmzf -") for path in to_delete: lines.append("rm -rf -- {}".format(shlex.quote(path))) added = [path for code, path in to_copy if code == "A"] if added: lines.append("printf '%s\\n' {} > {}".format(" ".join(shlex.quote(path) for path in added), SYNC_MANIFEST)) else: lines.append(": > {}".format(SYNC_MANIFEST)) return "\n".join(lines) + "\n" def command_script(config, command): """The shell that runs `command` in the copy, which sync_script has already changed into, kept awake.""" lines = [] if config["environment"]: lines.append(config["environment"]) lines.append("exec systemd-inhibit --what=sleep --who=remotebuild --why={} {}".format( shlex.quote("remotebuild in " + os.path.basename(REPO_ROOT)), command)) return "\n".join(lines) + "\n" def build_command(build_arguments): """The command that runs build.py there with `build_arguments`, never stopping to wait for a keypress.""" return "python3 -B -u Scripts/build.py --no-interactive " + " ".join(shlex.quote(word) for word in build_arguments) def run_command(words, timeout_minutes): """The command that runs `words` there, killed if it runs past `timeout_minutes`.""" return "timeout --kill-after=30s {}m {}".format(timeout_minutes, " ".join(shlex.quote(word) for word in words)) def magic_packet(mac): """The Wake-on-LAN packet for `mac`: six 0xFF bytes, then the address sixteen times.""" address = bytes(int(byte, 16) for byte in re.split(r"[:-]", mac)) if len(address) != 6: raise SystemExit("{} isn't a MAC address.".format(mac)) return b"\xff" * 6 + address * 16 def reachable(host): """Whether ssh can log in to `host` within a few seconds.""" return subprocess.run(["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=5", host, "true"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0 def wake(config): """Wakes the machine if ssh can't reach it, and waits until it can.""" host = config["host"] if reachable(host): return if not config["wake_mac"]: raise SystemExit("ssh can't reach {}, and {} gives no wake_mac to wake it with.".format(host, CONFIG_PATH)) with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sender: sender.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sender.sendto(magic_packet(config["wake_mac"]), (config["wake_broadcast"], 9)) print("Woke {}, waiting for ssh...".format(host), flush=True) deadline = time.monotonic() + config["wake_timeout_seconds"] while time.monotonic() < deadline: if reachable(host): return time.sleep(2) raise SystemExit("{} didn't answer ssh within {} seconds of waking.".format(host, config["wake_timeout_seconds"])) def run_remotely(config, script, stdin_bytes, keep_color): """Runs `script` under bash on the machine, feeding it `stdin_bytes`, and streams back what it prints. Returns: The script's exit code. """ process = subprocess.Popen( ["ssh", "-o", "BatchMode=yes", "-o", "ServerAliveInterval=30", config["host"], "bash -c " + shlex.quote(script)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) # On a thread of its own, since the script can print before it has read everything it's fed. def feed(): process.stdin.write(stdin_bytes) process.stdin.close() feeder = threading.Thread(target=feed, daemon=True) feeder.start() for raw_line in process.stdout: line = raw_line.decode("utf-8", errors="replace") if not keep_color: line = ANSI_ESCAPE.sub("", line) sys.stdout.write(line) sys.stdout.flush() feeder.join() return process.wait() USAGE = """usage: remotebuild.py [--keep-color] build [build.py arguments...] remotebuild.py [--keep-color] run [--timeout-minutes N] [--] command [arguments...] remotebuild.py sync""" DEFAULT_RUN_TIMEOUT_MINUTES = 30 def parse_arguments(argv): """The command line, with everything after `build`, or after `run`'s own options, passed on untouched. Parsed by hand, since argparse takes a passed-on `--project` for an option it doesn't know. """ words = list(argv) if words[:1] in (["-h"], ["--help"]): print(__doc__ + "\n" + USAGE) raise SystemExit(0) keep_color = words[:1] == ["--keep-color"] if keep_color: words = words[1:] if not words or words[0] not in ("build", "run", "sync"): raise SystemExit(USAGE) subcommand = words.pop(0) timeout_minutes = DEFAULT_RUN_TIMEOUT_MINUTES if subcommand == "run": if words[:1] == ["--timeout-minutes"] and len(words) > 1: timeout_minutes = int(words[1]) words = words[2:] if words[:1] == ["--"]: words = words[1:] if not words: raise SystemExit("run needs a command.\n" + USAGE) elif subcommand == "sync" and words: raise SystemExit("sync takes no arguments.\n" + USAGE) return argparse.Namespace(keep_color=keep_color, subcommand=subcommand, words=words, timeout_minutes=timeout_minutes) def main(argv): arguments = parse_arguments(argv) config = load_config() root_revision, external_revisions, to_copy, to_delete = local_state(REPO_ROOT) script = sync_script(config, copy_name(REPO_ROOT), root_revision, external_revisions, to_copy, to_delete) if arguments.subcommand == "build": script += command_script(config, build_command(arguments.words)) elif arguments.subcommand == "run": script += command_script(config, run_command(arguments.words, arguments.timeout_minutes)) else: script += 'echo "Synced {} changed and {} deleted files into $copy."\n'.format(len(to_copy), len(to_delete)) paths = [path for _, path in to_copy] archive = tar_of(REPO_ROOT, paths, native_eol_paths(REPO_ROOT, paths)) wake(config) return run_remotely(config, script, archive, arguments.keep_color) if __name__ == "__main__": sys.exit(main(sys.argv[1:]))