Buckets:

download
raw
10.3 kB
"""One compose document, at the repo root, for runtimes that need one.
Docker Compose v2 takes an ordered ``-f`` list and merges it itself, keyed on
the project directory the invocation pins. podman-compose does not behave that
way, and the difference is not a matter of taste — it decides where every
relative path in every rendered compose file resolves:
* podman-compose **1.0.6 – 1.3.0** chdir TWICE while assembling the project,
and the final working directory is the dirname of the FIRST ``-f`` file. It
overrides ``COMPOSE_PROJECT_DIR``, so there is no way to tell those versions
where the project root is.
* podman-compose **1.4.1+** chdir once, to ``COMPOSE_PROJECT_DIR``.
A ``-f`` list pointing into ``build/`` therefore resolves YAML-relative paths
(``env_file:`` entries, bind mounts, the web stack's files) against ``build/``
on one version and against the repo root on the next — from identical inputs,
with no error anywhere, and a stack that comes up reading the wrong files.
Merging the list into ONE document *at the repo root* removes the fork rather
than branching on it: the first (and only) ``-f`` file's dirname IS the repo
root, so the ≤ 1.3 chdir lands exactly where ``COMPOSE_PROJECT_DIR`` would have
put 1.4.1+, and where docker's ``--project-directory`` puts docker. One base,
every provider.
WHAT THIS FILE IS, AND IS NOT
=============================
``.osprey-compose.yml`` is a machine artifact — derived, disposable, and
classified as such everywhere it could be mistaken for source: git-ignored
(anchored to the root, so the pattern cannot swallow a same-named file moved
deeper in the tree), excluded from every container image's build context, and
on ``osprey reset``'s removal list. Nothing reads it back; the next deploy
rewrites it whole.
It carries no secrets. ``${VAR}`` references are copied through **unresolved**,
exactly as the rendered compose files spell them — interpolation stays the
runtime's job, fed by the ``--env-file`` the invocation passes. A merge that
substituted values here would bake the deployment's tokens into a file at the
repo root, which is the one place they must never be.
The merge itself mirrors compose's own ``-f`` semantics for the shape OSPREY
renders: mappings are merged key by key with later files winning, and anything
that is not a mapping is replaced outright by the later value. OSPREY's
rendered files carry disjoint ``services:`` maps (one file per deployed
service) plus the top-level file's ``networks:``/``volumes:``, so the merge is
in practice a union — but the precedence rule is stated and tested, because a
future template that does overlap must resolve the way compose would.
"""
from __future__ import annotations
import os
import tempfile
from collections.abc import Iterable, Mapping
from pathlib import Path
from typing import Any
import yaml
from osprey.deployment.errors import DeploymentError
from osprey.utils.logger import get_logger
logger = get_logger("deployment.compose_merge")
#: The merged document's name, at the deployment repo's ROOT. The location is
#: the whole point (see the module docstring) and the leading dot marks it as
#: machinery rather than something an operator edits. Every classification of
#: the artifact — the two ``.gitignore`` sources, the image-context exclusion in
#: :mod:`osprey.cli.build_cmd`, ``osprey reset``'s removal list — imports this
#: name rather than spelling it again.
MERGED_COMPOSE_FILENAME = ".osprey-compose.yml"
#: Header of the written file. Fixed text: the artifact's bytes are a function
#: of its inputs and nothing else, so a timestamp or a host path here would make
#: two identical merges differ.
_HEADER = f"""\
# {MERGED_COMPOSE_FILENAME} — generated by `osprey up`. Do not edit.
#
# The deployment's rendered compose files, merged into one document so that a
# single `-f` is enough. Regenerated on every deploy; `osprey reset` removes
# it. Edit the templates the render came from, not this.
#
# ${{VAR}} references are deliberately left unresolved — they are interpolated
# by the container runtime from the deployment's env files, so no value from
# .env is ever written here.
"""
#: File mode for the artifact. Readable, unlike the 0600 the ``.env`` writers
#: use: this file holds no secrets, and a mode that implied it did would be a
#: claim about its contents that is not true.
_FILE_MODE = 0o644
class ComposeMergeError(DeploymentError):
"""A compose file could not be merged into the root document.
Raised when a file in the ``-f`` list does not parse as YAML, or parses as
something other than a mapping. Both mean the render is broken in a way the
merge cannot paper over: writing a partial document would hand the runtime
a project missing services it was told to start.
"""
def merged_compose_path(repo_root: Path | str) -> Path:
"""Where the merged document lives for *repo_root* — the one spelling."""
return Path(repo_root).expanduser().absolute() / MERGED_COMPOSE_FILENAME
def merge_compose_documents(documents: Iterable[Mapping[str, Any]]) -> dict[str, Any]:
"""Deep-merge parsed compose documents in ``-f`` order, later files winning.
Mapping values are merged recursively; every other value (scalars, and
sequences such as ``ports:`` or ``env_file:``) is replaced whole by the
later document's, which is how compose resolves a key two files both set.
Key ORDER is the first document's, with keys a later document introduces
appended in the order they appear. That is what makes the written bytes a
function of the input alone — the same files in the same order always
produce the same file, and a diff between two deploys shows only what
actually changed.
:param documents: Parsed compose documents, in ``-f`` order.
:return: A new merged mapping. The inputs are never mutated.
"""
merged: dict[str, Any] = {}
for document in documents:
_merge_into(merged, document)
return merged
def render_merged_compose(documents: Iterable[Mapping[str, Any]]) -> str:
"""The merged document as the text written to disk, header included.
Separate from :func:`write_merged_compose` so the bytes can be asserted on
without a filesystem, and so a caller that wants to compare against what is
already on disk can do it without writing first.
"""
merged = merge_compose_documents(documents)
body = yaml.safe_dump(
merged,
sort_keys=False,
default_flow_style=False,
allow_unicode=True,
width=4096,
)
return f"{_HEADER}\n{body}"
def write_merged_compose(repo_root: Path | str, compose_files: Iterable[Path | str]) -> Path:
"""Merge *compose_files* into ``<repo_root>/.osprey-compose.yml``.
The deploy-side half of the provider-compat invocation: the caller hands
over the same ordered ``-f`` list docker would have been given, and gets
back the single absolute path to pass instead.
Written atomically through a same-directory temp file, so a deploy
interrupted mid-write leaves either the previous document or none — never a
truncated one that a runtime would happily parse as a project with half its
services missing.
:param repo_root: The deployment repo root. The document goes at its top
level, because that is where the ≤ 1.3 podman-compose chdir must land.
:param compose_files: Compose files in ``-f`` order. Relative paths are
resolved against *repo_root*, matching
:func:`osprey.deployment.compose_generator.compose_base_cmd`.
:return: Absolute path to the written document.
:raises ComposeMergeError: A listed file is missing, unparseable, or is not
a YAML mapping.
"""
root = Path(repo_root).expanduser().absolute()
documents = [_load_compose_document(_resolve(path, root)) for path in compose_files]
target = root / MERGED_COMPOSE_FILENAME
_atomic_write(target, render_merged_compose(documents))
logger.debug("Wrote merged compose document %s from %d file(s)", target, len(documents))
return target
def _resolve(path: Path | str, root: Path) -> Path:
candidate = Path(path)
return candidate if candidate.is_absolute() else root / candidate
def _load_compose_document(path: Path) -> dict[str, Any]:
"""Parse one compose file, refusing anything that is not a mapping.
An empty file is a mapping with nothing in it — a rendered service file
that came out empty contributes nothing rather than failing the deploy.
"""
try:
text = path.read_text(encoding="utf-8")
except OSError as exc:
raise ComposeMergeError(f"Cannot read compose file {path}: {exc}") from exc
try:
document = yaml.safe_load(text)
except yaml.YAMLError as exc:
raise ComposeMergeError(f"Cannot parse compose file {path}: {exc}") from exc
if document is None:
return {}
if not isinstance(document, Mapping):
raise ComposeMergeError(
f"Compose file {path} is a {type(document).__name__}, not a mapping. "
f"A compose document's top level is always keys (`services:`, "
f"`networks:`, `volumes:`), so this file cannot be merged."
)
return dict(document)
def _merge_into(target: dict[str, Any], source: Mapping[str, Any]) -> None:
"""Merge *source* into *target* in place, later-wins, mappings recursively."""
for key, value in source.items():
existing = target.get(key)
if isinstance(existing, dict) and isinstance(value, Mapping):
_merge_into(existing, value)
elif isinstance(value, Mapping):
nested: dict[str, Any] = {}
_merge_into(nested, value)
target[key] = nested
else:
target[key] = value
def _atomic_write(path: Path, text: str) -> None:
"""Write *text* to *path* via a same-directory temp file and ``os.replace``."""
fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=path.name, suffix=".tmp")
try:
with os.fdopen(fd, "w", encoding="utf-8") as handle:
handle.write(text)
os.chmod(tmp_name, _FILE_MODE)
os.replace(tmp_name, path)
except BaseException:
Path(tmp_name).unlink(missing_ok=True)
raise

Xet Storage Details

Size:
10.3 kB
·
Xet hash:
b617c1b2cbd37b0c4f0e8d5575290a1c502d743ec9376e74ab2aa3d9d47343cf

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.