|
| 1 | +# |
| 2 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 3 | +# or more contributor license agreements. See the NOTICE file |
| 4 | +# distributed with this work for additional information |
| 5 | +# regarding copyright ownership. The ASF licenses this file |
| 6 | +# to you under the Apache License, Version 2.0 (the |
| 7 | +# "License"); you may not use this file except in compliance |
| 8 | +# with the License. You may obtain a copy of the License at |
| 9 | +# |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +# |
| 12 | +# Unless required by applicable law or agreed to in writing, |
| 13 | +# software distributed under the License is distributed on an |
| 14 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | +# KIND, either express or implied. See the License for the |
| 16 | +# specific language governing permissions and limitations |
| 17 | +# under the License. |
| 18 | +"""Hot reload utilities for development mode.""" |
| 19 | + |
| 20 | +from __future__ import annotations |
| 21 | + |
| 22 | +import os |
| 23 | +import signal |
| 24 | +import sys |
| 25 | +from collections.abc import Callable, Sequence |
| 26 | +from pathlib import Path |
| 27 | +from typing import TYPE_CHECKING |
| 28 | + |
| 29 | +import structlog |
| 30 | + |
| 31 | +if TYPE_CHECKING: |
| 32 | + import subprocess |
| 33 | + |
| 34 | +log = structlog.getLogger(__name__) |
| 35 | + |
| 36 | + |
| 37 | +def run_with_reloader( |
| 38 | + callback: Callable, |
| 39 | + process_name: str = "process", |
| 40 | +) -> None: |
| 41 | + """ |
| 42 | + Run a callback function with automatic reloading on file changes. |
| 43 | +
|
| 44 | + This function monitors specified paths for changes and restarts the process |
| 45 | + when changes are detected. Useful for development mode hot-reloading. |
| 46 | +
|
| 47 | + :param callback: The function to run. This should be the main entry point |
| 48 | + of the command that needs hot-reload support. |
| 49 | + :param process_name: Name of the process being run (for logging purposes) |
| 50 | + """ |
| 51 | + # Default watch paths - watch the airflow source directory |
| 52 | + import airflow |
| 53 | + |
| 54 | + airflow_root = Path(airflow.__file__).parent |
| 55 | + watch_paths = [airflow_root] |
| 56 | + |
| 57 | + log.info("Starting %s in development mode with hot-reload enabled", process_name) |
| 58 | + log.info("Watching paths: %s", watch_paths) |
| 59 | + |
| 60 | + # Check if we're the main process or a reloaded child |
| 61 | + reloader_pid = os.environ.get("AIRFLOW_DEV_RELOADER_PID") |
| 62 | + if reloader_pid is None: |
| 63 | + # We're the main process - set up the reloader |
| 64 | + os.environ["AIRFLOW_DEV_RELOADER_PID"] = str(os.getpid()) |
| 65 | + _run_reloader(watch_paths) |
| 66 | + else: |
| 67 | + # We're a child process - just run the callback |
| 68 | + callback() |
| 69 | + |
| 70 | + |
| 71 | +def _terminate_process_tree( |
| 72 | + process: subprocess.Popen[bytes], |
| 73 | + timeout: int = 5, |
| 74 | + force_kill_remaining: bool = True, |
| 75 | +) -> None: |
| 76 | + """ |
| 77 | + Terminate a process and all its children recursively. |
| 78 | +
|
| 79 | + Uses psutil to ensure all child processes are properly terminated, |
| 80 | + which is important for cleaning up subprocesses like serve-log servers. |
| 81 | +
|
| 82 | + :param process: The subprocess.Popen process to terminate |
| 83 | + :param timeout: Timeout in seconds to wait for graceful termination |
| 84 | + :param force_kill_remaining: If True, force kill processes that don't terminate gracefully |
| 85 | + """ |
| 86 | + import subprocess |
| 87 | + |
| 88 | + import psutil |
| 89 | + |
| 90 | + try: |
| 91 | + parent = psutil.Process(process.pid) |
| 92 | + # Get all child processes recursively |
| 93 | + children = parent.children(recursive=True) |
| 94 | + |
| 95 | + # Terminate all children first |
| 96 | + for child in children: |
| 97 | + try: |
| 98 | + child.terminate() |
| 99 | + except (psutil.NoSuchProcess, psutil.AccessDenied): |
| 100 | + pass |
| 101 | + |
| 102 | + # Terminate the parent |
| 103 | + parent.terminate() |
| 104 | + |
| 105 | + # Wait for all processes to terminate |
| 106 | + gone, alive = psutil.wait_procs(children + [parent], timeout=timeout) |
| 107 | + |
| 108 | + # Force kill any remaining processes if requested |
| 109 | + if force_kill_remaining: |
| 110 | + for proc in alive: |
| 111 | + try: |
| 112 | + log.warning("Force killing process %s", proc.pid) |
| 113 | + proc.kill() |
| 114 | + except (psutil.NoSuchProcess, psutil.AccessDenied): |
| 115 | + pass |
| 116 | + |
| 117 | + except (psutil.NoSuchProcess, psutil.AccessDenied): |
| 118 | + # Process already terminated |
| 119 | + pass |
| 120 | + except Exception as e: |
| 121 | + log.warning("Error terminating process tree: %s", e) |
| 122 | + # Fallback to simple termination |
| 123 | + try: |
| 124 | + process.terminate() |
| 125 | + process.wait(timeout=timeout) |
| 126 | + except subprocess.TimeoutExpired: |
| 127 | + if force_kill_remaining: |
| 128 | + log.warning("Process did not terminate gracefully, killing...") |
| 129 | + process.kill() |
| 130 | + process.wait() |
| 131 | + |
| 132 | + |
| 133 | +def _run_reloader(watch_paths: Sequence[str | Path]) -> None: |
| 134 | + """ |
| 135 | + Watch for changes and restart the process. |
| 136 | +
|
| 137 | + Watches the provided paths and restarts the process by re-executing the |
| 138 | + Python interpreter with the same arguments. |
| 139 | +
|
| 140 | + :param watch_paths: List of paths to watch for changes. |
| 141 | + """ |
| 142 | + import subprocess |
| 143 | + |
| 144 | + from watchfiles import watch |
| 145 | + |
| 146 | + process = None |
| 147 | + should_exit = False |
| 148 | + |
| 149 | + def start_process(): |
| 150 | + """Start or restart the subprocess.""" |
| 151 | + nonlocal process |
| 152 | + if process is not None: |
| 153 | + log.info("Stopping process and all its children...") |
| 154 | + _terminate_process_tree(process, timeout=5, force_kill_remaining=True) |
| 155 | + |
| 156 | + log.info("Starting process...") |
| 157 | + # Restart the process by re-executing Python with the same arguments |
| 158 | + # Note: sys.argv is safe here as it comes from the original CLI invocation |
| 159 | + # and is only used in development mode for hot-reloading the same process |
| 160 | + process = subprocess.Popen([sys.executable] + sys.argv) |
| 161 | + return process |
| 162 | + |
| 163 | + def signal_handler(signum, frame): |
| 164 | + """Handle termination signals.""" |
| 165 | + nonlocal should_exit, process |
| 166 | + should_exit = True |
| 167 | + log.info("Received signal %s, shutting down...", signum) |
| 168 | + if process: |
| 169 | + _terminate_process_tree(process, timeout=5, force_kill_remaining=False) |
| 170 | + sys.exit(0) |
| 171 | + |
| 172 | + # Set up signal handlers |
| 173 | + signal.signal(signal.SIGINT, signal_handler) |
| 174 | + signal.signal(signal.SIGTERM, signal_handler) |
| 175 | + |
| 176 | + # Start the initial process |
| 177 | + process = start_process() |
| 178 | + |
| 179 | + log.info("Hot-reload enabled. Watching for file changes...") |
| 180 | + log.info("Press Ctrl+C to stop") |
| 181 | + |
| 182 | + try: |
| 183 | + for changes in watch(*watch_paths): |
| 184 | + if should_exit: |
| 185 | + break |
| 186 | + |
| 187 | + log.info("Detected changes: %s", changes) |
| 188 | + log.info("Reloading...") |
| 189 | + |
| 190 | + # Restart the process |
| 191 | + process = start_process() |
| 192 | + |
| 193 | + except KeyboardInterrupt: |
| 194 | + log.info("Shutting down...") |
| 195 | + if process: |
| 196 | + process.terminate() |
| 197 | + process.wait() |
0 commit comments