diff --git a/docs/user/images.md b/docs/user/images.md index 51632431..c89c6643 100644 --- a/docs/user/images.md +++ b/docs/user/images.md @@ -16,9 +16,10 @@ clears. Every file in an image is owned by uid and gid 0, so a setgid `tty` bina the root group. Replace suid and sgid executables with socket-activated services and other safer alternatives. -`image.ops.copy` gives a copied file mode 0755 if it is executable and 0644 otherwise, and creates missing -directories with mode 0755. git only stores the executable bit, so the image doesn't depend on the umask of -your checkout. To give a file another mode, run `chmod` in an `image.ops.run()` operation. +When `image.ops.copy` copies a file from the project or from a target, it gives the file mode 0755 if it is +executable and 0644 otherwise, and creates missing directories with mode 0755. git only stores the executable +bit, so the image doesn't depend on the umask of your checkout. A copy of an `image.layer()` keeps the modes of +the layer instead. To give a file another mode, run `chmod` in an `image.ops.run()` operation. Image operations see the modes, modification times, user extended attributes and explicit hardlinks of their parent snapshot. Snapshots keep nanosecond timestamps, and capture clamps them to `SOURCE_DATE_EPOCH`. Cpio @@ -247,9 +248,12 @@ and persists exactly one snapshot: at `/buildroot` or has it as its own root; in the chrooted case nothing of the interpreter reaches the snapshot, because the project bind carrying it lives under `/run`. - `image.ops.copy` introduces a declared Buck artifact at an absolute image path; `image.ops.mkdir` and - `image.ops.symlink` mutate the same root. `image.ops.remove` treats its absolute path as a glob pattern, - including recursive `**`, and removes every matching file, symlink, or directory tree. A pattern that - matches nothing does nothing. + `image.ops.symlink` mutate the same root. Given an `image.layer()` target, `image.ops.copy` copies the tree + of the layer, including the files of its parents, with the modes, extended attributes and hardlinks it has + in the layer. The destination must be missing or an empty directory, and it gets the mode of the root + directory of the layer. A product such as an `image.archive()` or a DDI is copied as its file. + `image.ops.remove` treats its absolute path as a glob pattern, including recursive `**`, and removes every + matching file, symlink, or directory tree. A pattern that matches nothing does nothing. - `image.ops.depmod()`, `image.ops.hwdb()`, `image.ops.locale_gen()` and `image.ops.preset()` build the state installed packages only describe (below). - `image.ops.install_from` installs what another target needs and applies the operations it attaches (see diff --git a/examples/image/BUCK b/examples/image/BUCK index 693b64f2..84e0872a 100644 --- a/examples/image/BUCK +++ b/examples/image/BUCK @@ -64,7 +64,7 @@ image.archive( ops = [ image.ops.run(["/usr/bin/mkdir", "-p", "/buildroot/etc/tine"]), image.ops.run(["/usr/bin/cp", "$(location :marker.txt)", "/buildroot/etc/tine/from-location"]), - # image.ops.copy() takes a source directly, so it needs no $(location) around the label. + # image.ops.copy() takes the label directly, so it needs no $(location) around it. image.ops.copy(":marker.txt", "/etc/tine/from-copy"), # A chrooted command runs with the image's own binaries. Buck's macro parser claims # `$(...)`, so the shell substitution is escaped. @@ -122,6 +122,29 @@ image.archive( format = "tar", ) +# A copy of a layer contains the tree of the layer, with the files of its parents. +image.archive( + name = "copied-layer", + parent = ":chained-base", + ops = [image.ops.copy(":chained-child.layer", "/usr/share/tine/chained")], + format = "tar", +) + +# The copy contains the file that the layer adds and the file it keeps from its parent, and leaves out +# the file that the layer removes. +box.sh_test( + name = "copied-layer-test", + labels = ["image"], + box = "@tine//tools:dev.box", + script = """ +grep -q '"name":"usr/share/tine/chained/etc/tine/from-child"' "$1" +grep -q '"name":"usr/share/tine/chained/etc/tine/from-base-kept"' "$1" +! grep -q '"name":"usr/share/tine/chained/etc/tine/from-base-gone"' "$1" +""", + args = ["$(location :copied-layer[manifest])"], + distro = _FEDORA, +) + # One layer installs packages and runs commands. image.layer( name = "layered-install-base", diff --git a/image/BUCK b/image/BUCK index eb9b326e..031e0a1e 100644 --- a/image/BUCK +++ b/image/BUCK @@ -36,6 +36,7 @@ python.binary( "//package:installer", "//rootfs:rootfs", "//rootfs:storage", + "//uapi16:uapi16", ], visibility = ["PUBLIC"], ) diff --git a/image/image.bzl b/image/image.bzl index 777b6992..66e28b50 100644 --- a/image/image.bzl +++ b/image/image.bzl @@ -241,6 +241,11 @@ def image_providers( image.sbom, ] + extra +# Only an `image.layer()` target provides ImageLayerInfo. `image.ops.copy()` copies the tree of a target that +# provides it, and copies every other target as its default output. A product such as an archive provides +# ImageInfo as well, so ImageInfo can't tell a layer from a product. +ImageLayerInfo = provider(fields = {}) + ImageInstallInfo = provider( doc = "Packages and operations a target contributes to any image installing it.", fields = { @@ -312,13 +317,27 @@ def _remove(path: Selectable) -> LayerOperation: return ("remove", path) def _copy(source: SelectableArtifact | None, destination: Selectable) -> LayerOperation: - """Copy a declared artifact to an absolute path in the image. + """Copy a declared artifact or the tree of an image layer to an absolute path in the image. + + A layer's tree keeps the modes, extended attributes and hardlinks it has in the layer. The destination + must not exist yet or be an empty directory, and it gets the mode of the layer's root directory. A `select()` may resolve `source` to `None`, in which case nothing is copied: that is how a tree only some distributions ship is one operation rather than a target per distribution. """ return ("copy", source, destination) +def _copy_source(source: Dependency | Artifact) -> Artifact | list[Artifact]: + """Resolve the source of a copy to an artifact, or to the snapshot stores of an image layer.""" + if isinstance(source, Artifact): + return source + if source.get(ImageLayerInfo) != None: + return source[ImageInfo].layers + outputs = source[DefaultInfo].default_outputs + if len(outputs) != 1: + fail("image copy: {} must have exactly one default output, not {}".format(source.label, len(outputs))) + return outputs[0] + def _install_from(target: str) -> LayerOperation: """Install what an `image_install()` target needs and apply the operations it attaches.""" return ("install_from", target) @@ -336,9 +355,10 @@ def expand_install_from(ops: list[typing.Any]) -> (list[str], list[typing.Any]): info = operation[1][ImageInstallInfo] packages += info.packages expanded += info.operations - elif operation[0] == "copy" and operation[1] == None: - # A select chose no source for this configuration. - pass + elif operation[0] == "copy": + # A select can choose no source for this configuration. + if operation[1] != None: + expanded.append(("copy", _copy_source(operation[1]), operation[2])) else: expanded.append(operation) return packages, expanded @@ -768,7 +788,9 @@ IMAGE_OPERATION_ATTR = attrs.one_of( ), attrs.tuple( attrs.enum(["copy"]), - attrs.option(attrs.source(allow_directory = True)), + # A label coerces as a dependency, so that expand_install_from() can tell a layer from other + # targets. A project path is not a label and coerces as a source. + attrs.option(attrs.one_of(attrs.dep(), attrs.source(allow_directory = True))), attrs.string(), ), attrs.tuple( @@ -839,6 +861,7 @@ def _image_impl(ctx: AnalysisContext) -> list[Provider]: return image_providers( default_outputs = image.layers[-1:], image = image, + extra = [ImageLayerInfo()], ) _image = rule( @@ -905,9 +928,12 @@ def _image_install_impl(ctx: AnalysisContext) -> list[Provider]: copies = {} for operation in operations: if operation[0] == "copy": - copies[operation[1].short_path] = operation[1] + # Stores of different targets can have the same short path, such as `snapshot`. The copies are + # therefore keyed by artifact. + for source in operation[1] if isinstance(operation[1], list) else [operation[1]]: + copies[source] = None return [ - DefaultInfo(default_outputs = [copies[path] for path in sorted(copies)]), + DefaultInfo(default_outputs = list(copies)), ImageInstallInfo( operations = operations, packages = sorted({package: None for package in ctx.attrs.packages + from_targets}), diff --git a/image/layer.py b/image/layer.py index 6f239d8f..fbd0413f 100755 --- a/image/layer.py +++ b/image/layer.py @@ -25,6 +25,7 @@ import installer import rootfs import storage +import uapi16 from isolation import AT_FDCWD, Bind, Close, open_directory @@ -137,6 +138,16 @@ def _copy(source: Path, destination: Path) -> None: _copy_file(source, destination) +def _restore(stores: list[Path], destination: Path) -> None: + # storage.restore() overwrites an existing regular file and writes through an existing symlink. + # A copy into a destination with existing entries would therefore silently change files of the image. + if destination.is_symlink() or ( + destination.exists() and (not destination.is_dir() or any(destination.iterdir())) + ): + util.fail(f"image copy of a layer needs a missing or empty directory at {destination}") + storage.restore(uapi16.Snapshot(stores), destination) + + def _merge_os_release(raw_fields: object) -> None: """Merge quoted KEY="value" assignments into /usr/lib/os-release, replacing existing keys.""" fields = dict(_mapping("os_release", "fields", raw_fields)) @@ -327,6 +338,10 @@ def _apply(value: object, target: Path) -> None: util.fail(f"image copy source must be a relative project path: {source!r}") with _project_chroot(target): _copy(Path(PROJECT) / source, _destination(destination)) + case ["copy", list(stores), str(destination)]: + # The rule passes the snapshot stores of an image layer instead of a single source. + with _project_chroot(target): + _restore([Path(PROJECT) / cast(str, store) for store in stores], _destination(destination)) case ["os_release", raw_fields]: with rootfs.chroot(target): _merge_os_release(raw_fields) diff --git a/image/layer_test.py b/image/layer_test.py index 6f93ab72..957cb27f 100644 --- a/image/layer_test.py +++ b/image/layer_test.py @@ -172,6 +172,40 @@ def run(tag: str, cmd: object, env: object, cwd: str | None = None) -> None: self.assertFalse((tree / "cache.pyc").exists()) self.assertTrue((self.project / "cache.pyc").exists()) + def test_a_copied_layer_keeps_its_metadata(self) -> None: + # A copy whose source is the stores of a layer restores the tree of the layer at the + # destination. Capture a tree with a hardlink, a private mode and an extended attribute into + # two stores in the project, copy the stores into an image and check that the restored tree + # keeps the hardlink, the mode and the extended attribute. Then check that a copy into a + # directory that is not empty fails. + tree = self.scratch / "tree" + tree.mkdir() + (tree / "file").write_text("lower") + lower = self.project / "lower" + storage.capture(storage.Root(tree), lower, epoch=CAPTURE_EPOCH) + (tree / "private").write_text("upper") + (tree / "private").chmod(0o600) + os.link(tree / "private", tree / "linked") + os.setxattr(tree / "private", "user.test", b"value") + upper = self.project / "upper" + storage.capture(storage.Root(tree), upper, [str(lower)], epoch=CAPTURE_EPOCH) + + self._build([["copy", ["lower", "upper"], "/usr/share/copied"]]) + + with storage.root(uapi16.Snapshot([self.out])) as restored: + copied = restored.path / "usr/share/copied" + self.assertEqual((copied / "file").read_text(), "lower") + self.assertEqual((copied / "private").read_text(), "upper") + self.assertEqual(stat.S_IMODE((copied / "private").stat().st_mode), 0o600) + self.assertTrue((copied / "private").samefile(copied / "linked")) + self.assertEqual(os.getxattr(copied / "private", "user.test"), b"value") + + # The first copy creates files in /copied, so the second copy into /copied fails. + self.out = self.scratch / "again" + self.out.mkdir() + with self.assertRaisesRegex(SystemExit, "missing or empty directory"): + self._build([["copy", ["lower"], "/copied"], ["copy", ["upper"], "/copied"]]) + 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.