ephraimbuddy commented on code in PR #75498: URL: https://github.com/apache/airflow/pull/75498#discussion_r4613857145
########## airflow-core/src/airflow/dag_processing/bundles/filesystem_artifact_store.py: ########## @@ -0,0 +1,552 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +"""Shared-filesystem artifact store for manifest-backed Dag bundles.""" + +from __future__ import annotations + +import logging +import os +import shutil +import stat +import tempfile +import time +from contextlib import contextmanager, suppress +from fcntl import LOCK_EX, LOCK_NB, LOCK_UN, flock +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from airflow.dag_processing.bundles._filesystem import ( + ensure_destination_is_within_root, + fsync_directory, + fsync_file, + fsync_tree_directories, + get_path_mode, + get_temp_snapshot_prefix, + raise_walk_error, + read_json_file, + remove_bundle_tree_forcefully, + remove_orphaned_temp_snapshots, +) +from airflow.dag_processing.bundles.artifact_store import ( + ArtifactStore, + BundleManifestNotFoundError, + BundleManifestRefDurabilityError, + PublishedSnapshot, +) +from airflow.dag_processing.bundles.manifest import ( + MANIFEST_FILE_NAME, + BundleManifestError, + BundleManifestSourceChangedError, + compute_file_sha256, + raise_source_access_error, + serialize_bundle_version_manifest, + validate_bundle_relative_path, +) + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + +log = logging.getLogger(__name__) + +DEFAULT_PUBLICATION_LOCK_TIMEOUT = 600.0 +_LOCK_POLL_INTERVAL = 1.0 +_LOCK_WAIT_LOG_INTERVAL = 30.0 + + +class FilesystemArtifactStore(ArtifactStore): + """ + Artifact store for a ``published_root`` on a filesystem shared by publishers and Airflow. + + Layout under ``published_root``: ``refs/<bundle>/latest.json`` (release reference), + ``versions/<bundle>/<version>/`` (snapshots) and ``_locks/<bundle>.lock`` (publication lock). + ``published_root`` must already exist; the store creates only the directories below it. + Provision it as a dedicated directory inside the shared filesystem so that a missing + mount also makes it disappear. An existing root, including the mount point itself, + does not prove the filesystem is mounted; deployments must ensure mount availability. + + Publishers need write access to the publication directories and read/write access to + the lock file. For different OS users, give ``published_root`` a shared publisher group + with group write and the setgid bit: new directories use those bits from ``published_root``. + + Publishers on different hosts serialize through ``flock`` on the lock file, so the + filesystem must enforce ``flock`` across hosts: NFSv4 does, NFSv3 only with the lock + manager (lockd) running, and FUSE or object-store mounts often accept ``flock`` without + enforcing it, which leaves concurrent publishers unserialized. + + Airflow never deletes published snapshots: a Dag run can request any version it pinned, + for example on a retry, rerun or callback. Snapshots are read-only and may be owned by + the publisher's OS user, so to prune one that no run can still request, remove it as + that user after adding the owner write bit (``chmod -R u+w``). + + :param lock_timeout: Seconds to wait for another publisher to release the lock before + failing. The lock is held while a whole snapshot is materialized, so allow for the + largest bundle on the slowest shared filesystem. + """ + + backend_type = "local" + + def __init__( + self, + *, + bundle_name: str, + published_root: Path, + lock_timeout: float = DEFAULT_PUBLICATION_LOCK_TIMEOUT, + ) -> None: + self.bundle_name = bundle_name + self._root = published_root + self._ref_path = published_root / "refs" / bundle_name / "latest.json" + self._snapshots_root = published_root / "versions" / bundle_name + self._lock_path = published_root / "_locks" / f"{bundle_name}.lock" + self._lock_timeout = lock_timeout + self._synced_dirs: set[Path] = set() + + @property + def published_root(self) -> Path: + """The ``published_root`` directory, for checks that need a filesystem path.""" + return self._root + + @property + def ref_locator(self) -> str: + return str(self._ref_path) + + def snapshot_locator(self, version: str) -> str: + return str(self._snapshots_root / version) + + def read_ref(self) -> dict[str, Any]: + return read_json_file( + self._ref_path, + missing_message=f"Bundle '{self.bundle_name}' has no release reference at {self._ref_path}", + invalid_message=( + f"Bundle '{self.bundle_name}' release reference {self._ref_path} is not a JSON object" + ), + ) + + def write_ref(self, payload: dict[str, Any]) -> None: + with _raise_storage_error(f"write release reference {self._ref_path}"): + self._ensure_publication_dir(self._ref_path.parent) + _write_json_atomically(self._ref_path, payload) + + @contextmanager + def publication_guard(self): + """Serialize publishers through a lock stored with the authoritative snapshots.""" + with _raise_storage_error(f"open publication lock {self._lock_path}"): + self._ensure_publication_dir(self._lock_path.parent) + # Linux NFS implements flock with fcntl locks, which require a writable + # descriptor for an exclusive lock. + try: + fd = os.open(self._lock_path, os.O_CREAT | os.O_RDWR, 0o664) + except PermissionError as e: + raise BundleManifestError( + f"Cannot open publication lock {self._lock_path}: publishers need read/write " + "access. Set its group to a shared publisher group and grant group read/write " + "access (chmod 0664), and ensure the lock directory is writable." + ) from e + with os.fdopen(fd, "r+b") as lock_file: + # os.open masks the mode with the umask; repair it whenever this publisher + # owns the file so other members of the publisher group can acquire it. + with _raise_storage_error(f"set permissions on publication lock {self._lock_path}"): + try: + os.fchmod(fd, stat.S_IMODE(os.fstat(fd).st_mode) | 0o664) + except OSError: + if os.fstat(fd).st_uid == os.geteuid(): + raise + self._acquire_publication_lock(lock_file) + published = False + try: + with _raise_storage_error(f"remove leftovers of failed publications under {self._root}"): + self._remove_publish_leftovers() + yield + published = True + finally: + # Unlock explicitly, not only through close(): a forked child sharing this open + # file description would keep holding the lock after this process closes it. + try: + flock(lock_file, LOCK_UN) + except OSError as e: + if published: + raise BundleManifestError( + f"Cannot release publication lock {self._lock_path}: {e}" + ) from e + # The publication's own error tells callers how to recover; keep it. + log.warning("Cannot release publication lock %s", self._lock_path, exc_info=True) + + def _acquire_publication_lock(self, lock_file) -> None: + deadline = time.monotonic() + self._lock_timeout + next_log_time = time.monotonic() + while True: + try: + flock(lock_file, LOCK_EX | LOCK_NB) + except BlockingIOError: + pass + except OSError as e: + raise BundleManifestError( + f"Cannot lock publication lock {self._lock_path}: {e}. The filesystem under " + "published_root must support flock across hosts; NFSv3 needs lockd." + ) from e + else: + return + now = time.monotonic() + if now >= deadline: + raise BundleManifestError( + f"Timed out after {self._lock_timeout:g}s waiting for publication lock " + f"{self._lock_path}; another publisher still holds it." + ) + if now >= next_log_time: + log.info("Waiting for publication lock %s held by another publisher", self._lock_path) + next_log_time = now + _LOCK_WAIT_LOG_INTERVAL + time.sleep(min(_LOCK_POLL_INTERVAL, deadline - now)) + + def prepare_publish_areas(self) -> None: + with _raise_storage_error(f"create publication directories under {self._root}"): + self._ensure_publication_dir(self._snapshots_root) + self._ensure_publication_dir(self._ref_path.parent) + + def snapshot_exists(self, version: str) -> bool: + with _raise_storage_error(f"check published snapshot {self._snapshots_root / version}"): + mode = get_path_mode(self._snapshots_root / version) + return mode is not None and stat.S_ISDIR(mode) + + def fetch_snapshot( + self, + version: str, + destination: Path, + *, + structural_validator: Callable[[Path], None], + ) -> None: + published_version_path = self._snapshots_root / version + with _raise_storage_error(f"fetch published snapshot {published_version_path}"): + published_mode = get_path_mode(published_version_path) + if published_mode is None or not stat.S_ISDIR(published_mode): + raise BundleManifestNotFoundError( + f"Bundle '{self.bundle_name}' version '{version}' is not published at " + f"{published_version_path}. Publish or restore the immutable snapshot before " + "running pinned work." + ) + if destination.exists() and any(destination.iterdir()): + raise ValueError(f"Snapshot fetch destination {destination} must be absent or empty") + structural_validator(published_version_path) + _copy_tree_contents(published_version_path, destination) + + def publish_snapshot( + self, + *, + manifest: dict[str, Any], + source_root: Path, + validate_existing: Callable[[Path], None], + ) -> PublishedSnapshot: + version_path = self._snapshots_root / manifest["version"] + with _raise_storage_error(f"publish snapshot {version_path}"): + version_mode = get_path_mode(version_path) + if version_mode is None: + created = _materialize_manifest_snapshot( + source_path=source_root, + manifest=manifest, + versions_dir=self._snapshots_root, + version_path=version_path, + ) + elif not stat.S_ISDIR(version_mode): + raise BundleManifestError( + f"Bundle snapshot path exists but is not a directory: {version_path}" + ) + else: + created = False + committed_manifest = manifest + if not created: + validate_existing(version_path) + manifest_file = version_path / MANIFEST_FILE_NAME + committed_manifest = read_json_file( + manifest_file, + missing_message=f"Bundle snapshot {version_path} has no manifest", + invalid_message=f"Bundle snapshot manifest {manifest_file} is not a JSON object", + ) + # An earlier attempt may have committed the snapshot and failed before this sync. + fsync_directory(self._snapshots_root) + return PublishedSnapshot(manifest=committed_manifest, created=created) + + def _remove_publish_leftovers(self) -> None: + remove_orphaned_temp_snapshots(self._snapshots_root) + _remove_orphaned_atomic_temp_files(self._ref_path) + + def _ensure_publication_dir(self, path: Path) -> None: + """Create a publication directory, syncing existing ones only on this store's first call for it.""" + _ensure_public_dir(path, root=self._root, sync_existing=path not in self._synced_dirs) + self._synced_dirs.add(path) + + +@contextmanager +def _raise_storage_error(action: str) -> Iterator[None]: + """ + Re-raise an ``OSError`` from published-artifact storage as a bundle error. + + A missing artifact becomes ``BundleManifestNotFoundError``; any other failure is a + ``BundleManifestError``, never ``BundleManifestSourceChangedError``, which publishers + treat as a benign concurrent edit of the source and retry quietly. + """ + try: + yield + except BundleManifestError: + raise + except FileNotFoundError as e: + raise BundleManifestNotFoundError(f"Cannot {action}: {e}") from e + except OSError as e: + raise BundleManifestError(f"Cannot {action}: {e}") from e + + +def _copy_file_contents(source: Path, destination: Path) -> None: + """ + Copy a file's bytes and permission bits, and none of its other metadata. + + Not ``shutil.copy2``: its ``copystat`` carries over ACLs and extended attributes, which the + chmods applied to snapshots and their cache copies do not clear. + """ + shutil.copy(source, destination) + + +def _copy_tree_contents(source_root: Path, destination: Path) -> None: + """Copy a tree with ``_copy_file_contents``; unlike ``shutil.copytree``, copy no directory metadata.""" + for dirpath, _, filenames in os.walk(source_root, onerror=raise_walk_error): + directory = destination / Path(dirpath).relative_to(source_root) + directory.mkdir(parents=True, exist_ok=True) + for filename in filenames: + _copy_file_contents(Path(dirpath) / filename, directory / filename) Review Comment: Done. THanks -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
