From 6f4aa3971ef2de9a6182cae23aa7aff6dcf11ec3 Mon Sep 17 00:00:00 2001 From: Daan De Meyer Date: Mon, 30 Nov 2026 14:46:33 +0100 Subject: [PATCH] image: Add image.ops.source() for tracked run arguments A run() or python() argument only becomes an input through $(location), so a project wraps every script it runs in an export_file(). A plain path to the script runs too, because the project is mounted in the sandbox. Buck doesn't track that file, though, and keeps the cached layer after the script changes. Let's add image.ops.source(), which names a file of the package as a tracked argument. The layer driver now fails on a plain argument that names a file of the project, so a script that isn't tracked breaks the build instead of leaving a stale image. Signed-off-by: Daan De Meyer --- docs/user/images.md | 13 ++++++++----- examples/image/BUCK | 16 +++------------- image/image.bzl | 28 +++++++++++++++++++++------- image/layer.py | 21 ++++++++++++++++++++- image/layer_test.py | 25 +++++++++++++++++++++---- 5 files changed, 73 insertions(+), 30 deletions(-) diff --git a/docs/user/images.md b/docs/user/images.md index 65189bc8..c629c1e3 100644 --- a/docs/user/images.md +++ b/docs/user/images.md @@ -246,11 +246,14 @@ and persists exactly one snapshot: - `image.ops.run([...])` executes a command against the image. By default the box supplies the userspace and the image is mounted at `/buildroot`; with `chroot = True` the command runs inside the image with its own binaries instead. Either takes an `env` argument that overlays variables on that command's - environment. An argument names a build artifact by being one, or by spelling `$(location //target)` in - a BUCK file, and it resolves the same in both modes: a chrooted command gets the project bind-mounted - read-only at a fixed path under `/run`, which is also its working directory. Write generated files - to paths in the image rather than to the working directory. Running a script the repository - owns is therefore just `image.ops.run(["/usr/bin/bash", "$(location :setup.sh)"], chroot = True)`. Buck's + environment. An argument names a build artifact by being one, by spelling `$(location //target)` in + a BUCK file, or by naming a file of the BUCK file's package with `image.ops.source("setup.sh")`. Buck + rebuilds the image when such a file changes. A plain argument that names a file of the project fails the + build, because Buck wouldn't rebuild the image when the file changes. Arguments resolve the same in both + modes: a chrooted command gets the project bind-mounted read-only at a fixed path under `/run`, which is + also its working directory. Write generated files to paths in the image rather than to the working + directory. To run a script of the package, use + `image.ops.run(["/usr/bin/bash", image.ops.source("setup.sh")], chroot = True)`. Buck's macro parser claims `$(...)`, so a shell substitution has to be written `\$(...)`; an unescaped one fails to parse rather than silently reaching the shell. - `image.ops.python([...])` runs a python script against the image without the image needing python: it is an diff --git a/examples/image/BUCK b/examples/image/BUCK index c458bfcd..3a28773f 100644 --- a/examples/image/BUCK +++ b/examples/image/BUCK @@ -31,16 +31,6 @@ export_file( src = "marker.txt", ) -export_file( - name = "configure.sh", - src = "configure.sh", -) - -export_file( - name = "configure.py", - src = "configure.py", -) - export_file( name = "manifest_check.py", src = "manifest_check.py", @@ -70,18 +60,18 @@ image.archive( # `$(...)`, so the shell substitution is escaped. image.ops.run(["/usr/bin/bash", "-c", "echo built-by-\\$(echo tine) > /etc/tine/marker"], chroot = True), # A repository-owned script, run inside the image. The project is mounted there, so - # `$(location)` names the script and its data exactly as it would outside. + # image.ops.source() and `$(location)` name the script and its data exactly as they would outside. image.ops.run( [ "/usr/bin/bash", - "$(location :configure.sh)", + image.ops.source("configure.sh"), "$(location :marker.txt)", "from-script-argument", ], chroot = True, ), # The same, in python, which this image does not install: the interpreter is Buck's own. - image.ops.python(["$(location :configure.py)", "$(location :marker.txt)", "from-python-argument"], chroot = True), + image.ops.python([image.ops.source("configure.py"), "$(location :marker.txt)", "from-python-argument"], chroot = True), # Unchrooted, the same interpreter sees the image at /buildroot, like any box command. image.ops.python(["-c", "from pathlib import Path; Path('/buildroot/etc/tine/from-python-box').write_text('x\\n')"]), # Ensure we don't leak the /tine sandbox mount into image builds diff --git a/image/image.bzl b/image/image.bzl index f1674e85..1e4e8152 100644 --- a/image/image.bzl +++ b/image/image.bzl @@ -262,7 +262,7 @@ SelectableArtifact = str | Artifact | Select # Operations replayed by the layer driver. -def _run(cmd: list[SelectableArtifact] | Select, env: dict[str, Selectable] = {}, chroot: bool | Select = False) -> LayerOperation: +def _run(cmd: list[SelectableArtifact | tuple] | Select, env: dict[str, Selectable] = {}, chroot: bool | Select = False) -> LayerOperation: """Run `cmd` against the image, either with the box's tooling or the image's own. By default the box supplies the userspace and the image is mounted at /buildroot. With @@ -271,13 +271,15 @@ def _run(cmd: list[SelectableArtifact] | Select, env: dict[str, Selectable] = {} either way and a script the repository owns can simply be run. A chrooted command writes its outputs to paths in the image because its project working directory is read-only. - An argument names a build artifact by being one, or by spelling `$(location //target)` in a - BUCK file. Buck's macro parser claims `$(...)`, so a shell substitution has to be written + An argument names a build artifact by being one, by spelling `$(location //target)` in a + BUCK file, or by naming a file of the BUCK file's package with `image.ops.source()`. A plain argument + that names a file of the project fails the build, because Buck doesn't rebuild the image when such a + file changes. Buck's macro parser claims `$(...)`, so a shell substitution has to be written `\\$(...)`; an unescaped one fails to parse rather than reaching the shell. """ return ("run", cmd, _environment(env), chroot) -def _python(cmd: list[SelectableArtifact], env: dict[str, Selectable] = {}, chroot: bool | Select = False) -> LayerOperation: +def _python(cmd: list[SelectableArtifact | tuple], env: dict[str, Selectable] = {}, chroot: bool | Select = False) -> LayerOperation: """Run a python script against the image, with the interpreter Buck already pins. `chroot` picks the image's view exactly as it does for `run`: mounted at /buildroot by default, @@ -293,6 +295,10 @@ def _python(cmd: list[SelectableArtifact], env: dict[str, Selectable] = {}, chro fail("python: cmd must not be empty") return ("python", cmd, _environment(env), chroot) +def _source(path: str) -> tuple: + """Name a file of the BUCK file's package as an argument of `run` or `python`.""" + return ("source", path) + def _environment(env: dict[str, Selectable]) -> dict[str, Selectable]: return {name: env[name] for name in sorted(env)} @@ -483,6 +489,7 @@ ops = struct( write_file = _write_file, remove = _remove, copy = _copy, + source = _source, merge_os_release = _merge_os_release, install_systemd_boot = _install_systemd_boot, depmod = _depmod, @@ -498,12 +505,19 @@ def _encode_operation(operation: LayerOperation, python: Dependency) -> LayerOpe # -B: the script and its imports are project sources, which no build may write bytecode into. prefix = [specs.executable(python), "-B"] if operation[0] == "python" else [] - # A box argument is a plain string, an artifact, or a resolved $(location) macro. + # A box argument is a plain string, an artifact, a source, or a resolved $(location) macro. + arguments = prefix + [argument[1] if isinstance(argument, tuple) else argument for argument in operation[1]] + + # The driver fails on a plain argument that names a file of the project. It skips the indexes of + # the arguments that Buck tracks as inputs. A $(location) macro resolves to a path below buck-out, + # which the driver skips as well. + inputs = [index for index, argument in enumerate(arguments) if index < len(prefix) or isinstance(argument, Artifact)] return ( "run", - prefix + [specs.argument(argument) for argument in operation[1]], + [specs.argument(argument) for argument in arguments], operation[2], operation[3], + inputs, ) def _install_specs( @@ -760,7 +774,7 @@ IMAGE_OPERATION_ATTR = attrs.one_of( # the same command with the interpreter the rule holds in front of it. attrs.tuple( attrs.enum(["run", "python"]), - attrs.list(attrs.arg()), + attrs.list(attrs.one_of(attrs.tuple(attrs.enum(["source"]), attrs.source()), attrs.arg())), attrs.dict(attrs.string(), attrs.string()), attrs.bool(), ), diff --git a/image/layer.py b/image/layer.py index fbd0413f..26970797 100755 --- a/image/layer.py +++ b/image/layer.py @@ -83,6 +83,24 @@ def _run(tag: str, raw_cmd: object, raw_env: object, cwd: str | None = None) -> util.fail(f"image op `{tag} {cmd}` failed (rc={rc})") +def _check_untracked(raw_cmd: object, raw_inputs: list[object]) -> None: + # The command runs in the project, so a relative argument can name a file of the project. Buck only + # rebuilds the image when an input changes, and a plain argument is not an input. Without this check, + # an edit of the file would leave the cached image unchanged. + if not isinstance(raw_cmd, list): + return + for index, arg in enumerate(raw_cmd): + if index in raw_inputs or not isinstance(arg, str) or not arg or arg.startswith("/"): + continue + if PurePosixPath(arg).parts[0] == "buck-out": + continue + if Path(arg).is_file(): + util.fail( + f"image op argument {arg!r} names a file of the project, but Buck doesn't track it. " + "Pass it with image.ops.source() or $(location)." + ) + + def _destination(value: str) -> Path: path = PurePosixPath(value) if not path.is_absolute() or ".." in path.parts: @@ -326,7 +344,8 @@ def _install(install: LayerInstall, target: Path, scratch: Path) -> None: def _apply(value: object, target: Path) -> None: operation = _operation(value) match operation: - case ["run", raw_cmd, raw_env, bool(chroot)]: + case ["run", raw_cmd, raw_env, bool(chroot), list(raw_inputs)]: + _check_untracked(raw_cmd, raw_inputs) if not chroot: _run("run", raw_cmd, raw_env) else: diff --git a/image/layer_test.py b/image/layer_test.py index 957cb27f..3872f58f 100644 --- a/image/layer_test.py +++ b/image/layer_test.py @@ -159,7 +159,7 @@ def run(tag: str, cmd: object, env: object, cwd: str | None = None) -> None: self._build( [ ["copy", "source", "/copied"], - ["run", ["command"], {}, True], + ["run", ["command"], {}, True, []], ["remove", "/**/*.pyc"], ], stored, @@ -206,6 +206,23 @@ def test_a_copied_layer_keeps_its_metadata(self) -> None: with self.assertRaisesRegex(SystemExit, "missing or empty directory"): self._build([["copy", ["lower"], "/copied"], ["copy", ["upper"], "/copied"]]) + def test_a_command_must_not_name_an_untracked_file_of_the_project(self) -> None: + # Buck only rebuilds an image when an input of the layer changes. A run argument that names a + # file of the project without being an input must fail the build. The project contains the + # file `source`. Check that a plain `source` argument fails, and that the same argument passes + # when the rule lists it as an input. + with mock.patch.object(layer, "_run") as command: + with self.assertRaisesRegex(SystemExit, "doesn't track it"): + self._build([["run", ["cat", "source"], {}, False, []]]) + command.assert_not_called() + + # Arguments that name no file of the project, such as a flag, an image path, a long + # shell snippet and a missing file, pass. + self._build( + [["run", ["cat", "-n", "/etc/os-release", "x" * 5000, "missing", "source"], {}, False, [5]]] + ) + command.assert_called_once() + def test_commands_see_inherited_metadata_and_can_override_it(self) -> None: # Capture before artifact copying, then check a command sees the original metadata and # explicit hardlinks. Its metadata changes must become authoritative in the child snapshot. @@ -229,7 +246,7 @@ def command(*args: object) -> None: os.utime(path, ns=(456, 456)) with mock.patch.object(layer, "_run", side_effect=command): - self._build([["run", ["command"], {}, False]], copied) + self._build([["run", ["command"], {}, False, []]], copied) with storage.root(uapi16.Snapshot([copied, self.out])) as restored: tree = restored.path self.assertEqual(stat.S_IMODE((tree / "file").stat().st_mode), 0o600) @@ -247,7 +264,7 @@ def command(*args: object) -> None: try: with mock.patch.object(layer, "_run", side_effect=command), self.assertRaises(OSError) as error: - self._build([["run", ["command"], {}, False]]) + self._build([["run", ["command"], {}, False, []]]) self.assertEqual(error.exception.errno, errno.EBUSY) self.assertFalse((self.out / uapi16.MANIFEST).exists()) finally: @@ -271,7 +288,7 @@ def command(*args: object) -> None: Path("/buildroot/linked").chmod(0o600) with mock.patch.object(layer, "_run", side_effect=command): - self._build([["run", ["command"], {}, False]], parent) + self._build([["run", ["command"], {}, False, []]], parent) with storage.root(uapi16.Snapshot([parent, self.out])) as restored: tree = restored.path self.assertTrue((tree / "file").samefile(tree / "linked"))