manager.py 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480
  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. """Processes DAGs."""
  19. from __future__ import annotations
  20. import enum
  21. import importlib
  22. import inspect
  23. import logging
  24. import multiprocessing
  25. import os
  26. import random
  27. import signal
  28. import sys
  29. import time
  30. import zipfile
  31. from collections import defaultdict, deque
  32. from datetime import datetime, timedelta
  33. from importlib import import_module
  34. from pathlib import Path
  35. from typing import TYPE_CHECKING, Any, Callable, Iterator, NamedTuple, cast
  36. from setproctitle import setproctitle
  37. from sqlalchemy import delete, select, update
  38. from tabulate import tabulate
  39. import airflow.models
  40. from airflow.api_internal.internal_api_call import internal_api_call
  41. from airflow.callbacks.callback_requests import CallbackRequest, SlaCallbackRequest
  42. from airflow.configuration import conf
  43. from airflow.dag_processing.processor import DagFileProcessorProcess
  44. from airflow.models.dag import DagModel
  45. from airflow.models.dagbag import DagPriorityParsingRequest
  46. from airflow.models.dagwarning import DagWarning
  47. from airflow.models.db_callback_request import DbCallbackRequest
  48. from airflow.models.errors import ParseImportError
  49. from airflow.models.serialized_dag import SerializedDagModel
  50. from airflow.secrets.cache import SecretCache
  51. from airflow.stats import Stats
  52. from airflow.traces.tracer import Trace, span
  53. from airflow.utils import timezone
  54. from airflow.utils.dates import datetime_to_nano
  55. from airflow.utils.file import list_py_file_paths, might_contain_dag
  56. from airflow.utils.log.logging_mixin import LoggingMixin
  57. from airflow.utils.mixins import MultiprocessingStartMethodMixin
  58. from airflow.utils.net import get_hostname
  59. from airflow.utils.process_utils import (
  60. kill_child_processes_by_pids,
  61. reap_process_group,
  62. set_new_process_group,
  63. )
  64. from airflow.utils.retries import retry_db_transaction
  65. from airflow.utils.session import NEW_SESSION, provide_session
  66. from airflow.utils.sqlalchemy import prohibit_commit, with_row_locks
  67. if TYPE_CHECKING:
  68. from multiprocessing.connection import Connection as MultiprocessingConnection
  69. from sqlalchemy.orm import Session
  70. class DagParsingStat(NamedTuple):
  71. """Information on processing progress."""
  72. done: bool
  73. all_files_processed: bool
  74. class DagFileStat(NamedTuple):
  75. """Information about single processing of one file."""
  76. num_dags: int
  77. import_errors: int
  78. last_finish_time: datetime | None
  79. last_duration: timedelta | None
  80. run_count: int
  81. last_num_of_db_queries: int
  82. class DagParsingSignal(enum.Enum):
  83. """All signals sent to parser."""
  84. AGENT_RUN_ONCE = "agent_run_once"
  85. TERMINATE_MANAGER = "terminate_manager"
  86. END_MANAGER = "end_manager"
  87. class DagFileProcessorAgent(LoggingMixin, MultiprocessingStartMethodMixin):
  88. """
  89. Agent for DAG file processing.
  90. It is responsible for all DAG parsing related jobs in scheduler process.
  91. Mainly it can spin up DagFileProcessorManager in a subprocess,
  92. collect DAG parsing results from it and communicate signal/DAG parsing stat with it.
  93. This class runs in the main `airflow scheduler` process.
  94. :param dag_directory: Directory where DAG definitions are kept. All
  95. files in file_paths should be under this directory
  96. :param max_runs: The number of times to parse and schedule each file. -1
  97. for unlimited.
  98. :param processor_timeout: How long to wait before timing out a DAG file processor
  99. :param dag_ids: if specified, only schedule tasks with these DAG IDs
  100. :param pickle_dags: whether to pickle DAGs.
  101. :param async_mode: Whether to start agent in async mode
  102. """
  103. def __init__(
  104. self,
  105. dag_directory: os.PathLike,
  106. max_runs: int,
  107. processor_timeout: timedelta,
  108. dag_ids: list[str] | None,
  109. pickle_dags: bool,
  110. async_mode: bool,
  111. ):
  112. super().__init__()
  113. self._dag_directory: os.PathLike = dag_directory
  114. self._max_runs = max_runs
  115. self._processor_timeout = processor_timeout
  116. self._dag_ids = dag_ids
  117. self._pickle_dags = pickle_dags
  118. self._async_mode = async_mode
  119. # Map from file path to the processor
  120. self._processors: dict[str, DagFileProcessorProcess] = {}
  121. # Pipe for communicating signals
  122. self._process: multiprocessing.process.BaseProcess | None = None
  123. self._done: bool = False
  124. # Initialized as true so we do not deactivate w/o any actual DAG parsing.
  125. self._all_files_processed = True
  126. self._parent_signal_conn: MultiprocessingConnection | None = None
  127. self._last_parsing_stat_received_at: float = time.monotonic()
  128. def start(self) -> None:
  129. """Launch DagFileProcessorManager processor and start DAG parsing loop in manager."""
  130. context = self._get_multiprocessing_context()
  131. self._last_parsing_stat_received_at = time.monotonic()
  132. self._parent_signal_conn, child_signal_conn = context.Pipe()
  133. process = context.Process(
  134. target=type(self)._run_processor_manager,
  135. args=(
  136. self._dag_directory,
  137. self._max_runs,
  138. self._processor_timeout,
  139. child_signal_conn,
  140. self._dag_ids,
  141. self._pickle_dags,
  142. self._async_mode,
  143. ),
  144. )
  145. self._process = process
  146. process.start()
  147. self.log.info("Launched DagFileProcessorManager with pid: %s", process.pid)
  148. def run_single_parsing_loop(self) -> None:
  149. """
  150. Send agent heartbeat signal to the manager, requesting that it runs one processing "loop".
  151. Should only be used when launched DAG file processor manager in sync mode.
  152. Call wait_until_finished to ensure that any launched processors have finished before continuing.
  153. """
  154. if not self._parent_signal_conn or not self._process:
  155. raise ValueError("Process not started.")
  156. if not self._process.is_alive():
  157. return
  158. try:
  159. self._parent_signal_conn.send(DagParsingSignal.AGENT_RUN_ONCE)
  160. except ConnectionError:
  161. # If this died cos of an error then we will noticed and restarted
  162. # when harvest_serialized_dags calls _heartbeat_manager.
  163. pass
  164. def get_callbacks_pipe(self) -> MultiprocessingConnection:
  165. """Return the pipe for sending Callbacks to DagProcessorManager."""
  166. if not self._parent_signal_conn:
  167. raise ValueError("Process not started.")
  168. return self._parent_signal_conn
  169. def wait_until_finished(self) -> None:
  170. """Wait until DAG parsing is finished."""
  171. if not self._parent_signal_conn:
  172. raise ValueError("Process not started.")
  173. if self._async_mode:
  174. raise RuntimeError("wait_until_finished should only be called in sync_mode")
  175. while self._parent_signal_conn.poll(timeout=None):
  176. try:
  177. result = self._parent_signal_conn.recv()
  178. except EOFError:
  179. return
  180. self._process_message(result)
  181. if isinstance(result, DagParsingStat):
  182. # In sync mode (which is the only time we call this function) we don't send this message from
  183. # the Manager until all the running processors have finished
  184. return
  185. @staticmethod
  186. def _run_processor_manager(
  187. dag_directory: os.PathLike,
  188. max_runs: int,
  189. processor_timeout: timedelta,
  190. signal_conn: MultiprocessingConnection,
  191. dag_ids: list[str] | None,
  192. pickle_dags: bool,
  193. async_mode: bool,
  194. ) -> None:
  195. # Make this process start as a new process group - that makes it easy
  196. # to kill all sub-process of this at the OS-level, rather than having
  197. # to iterate the child processes
  198. set_new_process_group()
  199. span = Trace.get_current_span()
  200. span.set_attribute("dag_directory", str(dag_directory))
  201. span.set_attribute("dag_ids", str(dag_ids))
  202. setproctitle("airflow scheduler -- DagFileProcessorManager")
  203. reload_configuration_for_dag_processing()
  204. processor_manager = DagFileProcessorManager(
  205. dag_directory=dag_directory,
  206. max_runs=max_runs,
  207. processor_timeout=processor_timeout,
  208. dag_ids=dag_ids,
  209. pickle_dags=pickle_dags,
  210. signal_conn=signal_conn,
  211. async_mode=async_mode,
  212. )
  213. processor_manager.start()
  214. def heartbeat(self) -> None:
  215. """Check if the DagFileProcessorManager process is alive, and process any pending messages."""
  216. if not self._parent_signal_conn:
  217. raise ValueError("Process not started.")
  218. # Receive any pending messages before checking if the process has exited.
  219. while self._parent_signal_conn.poll(timeout=0.01):
  220. try:
  221. result = self._parent_signal_conn.recv()
  222. except (EOFError, ConnectionError):
  223. break
  224. self._process_message(result)
  225. # If it died unexpectedly restart the manager process
  226. self._heartbeat_manager()
  227. def _process_message(self, message):
  228. span = Trace.get_current_span()
  229. self.log.debug("Received message of type %s", type(message).__name__)
  230. if isinstance(message, DagParsingStat):
  231. span.set_attribute("all_files_processed", str(message.all_files_processed))
  232. self._sync_metadata(message)
  233. else:
  234. raise RuntimeError(f"Unexpected message received of type {type(message).__name__}")
  235. def _heartbeat_manager(self):
  236. """Heartbeat DAG file processor and restart it if we are not done."""
  237. if not self._parent_signal_conn:
  238. raise ValueError("Process not started.")
  239. if self._process and not self._process.is_alive():
  240. self._process.join(timeout=0)
  241. if not self.done:
  242. self.log.warning(
  243. "DagFileProcessorManager (PID=%d) exited with exit code %d - re-launching",
  244. self._process.pid,
  245. self._process.exitcode,
  246. )
  247. self.start()
  248. if self.done:
  249. return
  250. parsing_stat_age = time.monotonic() - self._last_parsing_stat_received_at
  251. if parsing_stat_age > self._processor_timeout.total_seconds():
  252. Stats.incr("dag_processing.manager_stalls")
  253. self.log.error(
  254. "DagFileProcessorManager (PID=%d) last sent a heartbeat %.2f seconds ago! Restarting it",
  255. self._process.pid,
  256. parsing_stat_age,
  257. )
  258. reap_process_group(self._process.pid, logger=self.log)
  259. self.start()
  260. def _sync_metadata(self, stat):
  261. """Sync metadata from stat queue and only keep the latest stat."""
  262. self._done = stat.done
  263. self._all_files_processed = stat.all_files_processed
  264. self._last_parsing_stat_received_at = time.monotonic()
  265. @property
  266. def done(self) -> bool:
  267. """Whether the DagFileProcessorManager finished."""
  268. return self._done
  269. @property
  270. def all_files_processed(self):
  271. """Whether all files been processed at least once."""
  272. return self._all_files_processed
  273. def terminate(self):
  274. """Send termination signal to DAG parsing processor manager to terminate all DAG file processors."""
  275. if self._process and self._process.is_alive():
  276. self.log.info("Sending termination message to manager.")
  277. try:
  278. self._parent_signal_conn.send(DagParsingSignal.TERMINATE_MANAGER)
  279. except ConnectionError:
  280. pass
  281. def end(self):
  282. """Terminate (and then kill) the manager process launched."""
  283. if not self._process:
  284. self.log.warning("Ending without manager process.")
  285. return
  286. # Give the Manager some time to cleanly shut down, but not too long, as
  287. # it's better to finish sooner than wait for (non-critical) work to
  288. # finish
  289. self._process.join(timeout=1.0)
  290. reap_process_group(self._process.pid, logger=self.log)
  291. self._parent_signal_conn.close()
  292. class DagFileProcessorManager(LoggingMixin):
  293. """
  294. Manage processes responsible for parsing DAGs.
  295. Given a list of DAG definition files, this kicks off several processors
  296. in parallel to process them and put the results to a multiprocessing.Queue
  297. for DagFileProcessorAgent to harvest. The parallelism is limited and as the
  298. processors finish, more are launched. The files are processed over and
  299. over again, but no more often than the specified interval.
  300. :param dag_directory: Directory where DAG definitions are kept. All
  301. files in file_paths should be under this directory
  302. :param max_runs: The number of times to parse and schedule each file. -1
  303. for unlimited.
  304. :param processor_timeout: How long to wait before timing out a DAG file processor
  305. :param signal_conn: connection to communicate signal with processor agent.
  306. :param dag_ids: if specified, only schedule tasks with these DAG IDs
  307. :param pickle_dags: whether to pickle DAGs.
  308. :param async_mode: whether to start the manager in async mode
  309. """
  310. DEFAULT_FILE_STAT = DagFileStat(
  311. num_dags=0,
  312. import_errors=0,
  313. last_finish_time=None,
  314. last_duration=None,
  315. run_count=0,
  316. last_num_of_db_queries=0,
  317. )
  318. def __init__(
  319. self,
  320. dag_directory: os.PathLike[str],
  321. max_runs: int,
  322. processor_timeout: timedelta,
  323. dag_ids: list[str] | None,
  324. pickle_dags: bool,
  325. signal_conn: MultiprocessingConnection | None = None,
  326. async_mode: bool = True,
  327. ):
  328. super().__init__()
  329. # known files; this will be updated every `dag_dir_list_interval` and stuff added/removed accordingly
  330. self._file_paths: list[str] = []
  331. self._file_path_queue: deque[str] = deque()
  332. self._max_runs = max_runs
  333. # signal_conn is None for dag_processor_standalone mode.
  334. self._direct_scheduler_conn = signal_conn
  335. self._pickle_dags = pickle_dags
  336. self._dag_ids = dag_ids
  337. self._async_mode = async_mode
  338. self._parsing_start_time: float | None = None
  339. self._dag_directory = dag_directory
  340. # Set the signal conn in to non-blocking mode, so that attempting to
  341. # send when the buffer is full errors, rather than hangs for-ever
  342. # attempting to send (this is to avoid deadlocks!)
  343. #
  344. # Don't do this in sync_mode, as we _need_ the DagParsingStat sent to
  345. # continue the scheduler
  346. if self._async_mode and self._direct_scheduler_conn is not None:
  347. os.set_blocking(self._direct_scheduler_conn.fileno(), False)
  348. self.standalone_dag_processor = conf.getboolean("scheduler", "standalone_dag_processor")
  349. self._parallelism = conf.getint("scheduler", "parsing_processes")
  350. if (
  351. conf.get_mandatory_value("database", "sql_alchemy_conn").startswith("sqlite")
  352. and self._parallelism > 1
  353. ):
  354. self.log.warning(
  355. "Because we cannot use more than 1 thread (parsing_processes = "
  356. "%d) when using sqlite. So we set parallelism to 1.",
  357. self._parallelism,
  358. )
  359. self._parallelism = 1
  360. # Parse and schedule each file no faster than this interval.
  361. self._file_process_interval = conf.getint("scheduler", "min_file_process_interval")
  362. # How often to print out DAG file processing stats to the log. Default to
  363. # 30 seconds.
  364. self.print_stats_interval = conf.getint("scheduler", "print_stats_interval")
  365. # Map from file path to the processor
  366. self._processors: dict[str, DagFileProcessorProcess] = {}
  367. self._num_run = 0
  368. # Map from file path to stats about the file
  369. self._file_stats: dict[str, DagFileStat] = {}
  370. # Last time that the DAG dir was traversed to look for files
  371. self.last_dag_dir_refresh_time = timezone.make_aware(datetime.fromtimestamp(0))
  372. # Last time stats were printed
  373. self.last_stat_print_time = 0
  374. # Last time we cleaned up DAGs which are no longer in files
  375. self.last_deactivate_stale_dags_time = timezone.make_aware(datetime.fromtimestamp(0))
  376. # How often to check for DAGs which are no longer in files
  377. self.parsing_cleanup_interval = conf.getint("scheduler", "parsing_cleanup_interval")
  378. # How long to wait for a DAG to be reparsed after its file has been parsed before disabling
  379. self.stale_dag_threshold = conf.getint("scheduler", "stale_dag_threshold")
  380. # How long to wait before timing out a process to parse a DAG file
  381. self._processor_timeout = processor_timeout
  382. # How often to scan the DAGs directory for new files. Default to 5 minutes.
  383. self.dag_dir_list_interval = conf.getint("scheduler", "dag_dir_list_interval")
  384. # Mapping file name and callbacks requests
  385. self._callback_to_execute: dict[str, list[CallbackRequest]] = defaultdict(list)
  386. self._log = logging.getLogger("airflow.processor_manager")
  387. self.waitables: dict[Any, MultiprocessingConnection | DagFileProcessorProcess] = (
  388. {
  389. self._direct_scheduler_conn: self._direct_scheduler_conn,
  390. }
  391. if self._direct_scheduler_conn is not None
  392. else {}
  393. )
  394. self.heartbeat: Callable[[], None] = lambda: None
  395. def register_exit_signals(self):
  396. """Register signals that stop child processes."""
  397. signal.signal(signal.SIGINT, self._exit_gracefully)
  398. signal.signal(signal.SIGTERM, self._exit_gracefully)
  399. # So that we ignore the debug dump signal, making it easier to send
  400. signal.signal(signal.SIGUSR2, signal.SIG_IGN)
  401. def _exit_gracefully(self, signum, frame):
  402. """Clean up DAG file processors to avoid leaving orphan processes."""
  403. self.log.info("Exiting gracefully upon receiving signal %s", signum)
  404. self.log.debug("Current Stacktrace is: %s", "\n".join(map(str, inspect.stack())))
  405. self.terminate()
  406. self.end()
  407. self.log.debug("Finished terminating DAG processors.")
  408. sys.exit(os.EX_OK)
  409. def start(self):
  410. """
  411. Use multiple processes to parse and generate tasks for the DAGs in parallel.
  412. By processing them in separate processes, we can get parallelism and isolation
  413. from potentially harmful user code.
  414. """
  415. self.register_exit_signals()
  416. set_new_process_group()
  417. self.log.info("Processing files using up to %s processes at a time ", self._parallelism)
  418. self.log.info("Process each file at most once every %s seconds", self._file_process_interval)
  419. self.log.info(
  420. "Checking for new files in %s every %s seconds", self._dag_directory, self.dag_dir_list_interval
  421. )
  422. return self._run_parsing_loop()
  423. def _scan_stale_dags(self):
  424. """Scan at fix internal DAGs which are no longer present in files."""
  425. now = timezone.utcnow()
  426. elapsed_time_since_refresh = (now - self.last_deactivate_stale_dags_time).total_seconds()
  427. if elapsed_time_since_refresh > self.parsing_cleanup_interval:
  428. last_parsed = {
  429. fp: self.get_last_finish_time(fp) for fp in self.file_paths if self.get_last_finish_time(fp)
  430. }
  431. DagFileProcessorManager.deactivate_stale_dags(
  432. last_parsed=last_parsed,
  433. dag_directory=self.get_dag_directory(),
  434. stale_dag_threshold=self.stale_dag_threshold,
  435. )
  436. self.last_deactivate_stale_dags_time = timezone.utcnow()
  437. @classmethod
  438. @internal_api_call
  439. @provide_session
  440. def deactivate_stale_dags(
  441. cls,
  442. last_parsed: dict[str, datetime | None],
  443. dag_directory: str,
  444. stale_dag_threshold: int,
  445. session: Session = NEW_SESSION,
  446. ):
  447. """
  448. Detect DAGs which are no longer present in files.
  449. Deactivate them and remove them in the serialized_dag table.
  450. """
  451. to_deactivate = set()
  452. query = select(DagModel.dag_id, DagModel.fileloc, DagModel.last_parsed_time).where(DagModel.is_active)
  453. standalone_dag_processor = conf.getboolean("scheduler", "standalone_dag_processor")
  454. if standalone_dag_processor:
  455. query = query.where(DagModel.processor_subdir == dag_directory)
  456. dags_parsed = session.execute(query)
  457. for dag in dags_parsed:
  458. # The largest valid difference between a DagFileStat's last_finished_time and a DAG's
  459. # last_parsed_time is the processor_timeout. Longer than that indicates that the DAG is
  460. # no longer present in the file. We have a stale_dag_threshold configured to prevent a
  461. # significant delay in deactivation of stale dags when a large timeout is configured
  462. if (
  463. dag.fileloc in last_parsed
  464. and (dag.last_parsed_time + timedelta(seconds=stale_dag_threshold)) < last_parsed[dag.fileloc]
  465. ):
  466. cls.logger().info("DAG %s is missing and will be deactivated.", dag.dag_id)
  467. to_deactivate.add(dag.dag_id)
  468. if to_deactivate:
  469. deactivated_dagmodel = session.execute(
  470. update(DagModel)
  471. .where(DagModel.dag_id.in_(to_deactivate))
  472. .values(is_active=False)
  473. .execution_options(synchronize_session="fetch")
  474. )
  475. deactivated = deactivated_dagmodel.rowcount
  476. if deactivated:
  477. cls.logger().info("Deactivated %i DAGs which are no longer present in file.", deactivated)
  478. for dag_id in to_deactivate:
  479. SerializedDagModel.remove_dag(dag_id)
  480. cls.logger().info("Deleted DAG %s in serialized_dag table", dag_id)
  481. def _run_parsing_loop(self):
  482. # In sync mode we want timeout=None -- wait forever until a message is received
  483. if self._async_mode:
  484. poll_time = 0.0
  485. else:
  486. poll_time = None
  487. self._refresh_dag_dir()
  488. self.prepare_file_path_queue()
  489. max_callbacks_per_loop = conf.getint("scheduler", "max_callbacks_per_loop")
  490. if self._async_mode:
  491. # If we're in async mode, we can start up straight away. If we're
  492. # in sync mode we need to be told to start a "loop"
  493. self.start_new_processes()
  494. while True:
  495. with Trace.start_span(span_name="dag_parsing_loop", component="DagFileProcessorManager") as span:
  496. loop_start_time = time.monotonic()
  497. ready = multiprocessing.connection.wait(self.waitables.keys(), timeout=poll_time)
  498. if span.is_recording():
  499. span.add_event(name="heartbeat")
  500. self.heartbeat()
  501. if self._direct_scheduler_conn is not None and self._direct_scheduler_conn in ready:
  502. agent_signal = self._direct_scheduler_conn.recv()
  503. self.log.debug("Received %s signal from DagFileProcessorAgent", agent_signal)
  504. if agent_signal == DagParsingSignal.TERMINATE_MANAGER:
  505. if span.is_recording():
  506. span.add_event(name="terminate")
  507. self.terminate()
  508. break
  509. elif agent_signal == DagParsingSignal.END_MANAGER:
  510. if span.is_recording():
  511. span.add_event(name="end")
  512. self.end()
  513. sys.exit(os.EX_OK)
  514. elif agent_signal == DagParsingSignal.AGENT_RUN_ONCE:
  515. # continue the loop to parse dags
  516. pass
  517. elif isinstance(agent_signal, CallbackRequest):
  518. self._add_callback_to_queue(agent_signal)
  519. else:
  520. raise ValueError(f"Invalid message {type(agent_signal)}")
  521. if not ready and not self._async_mode:
  522. # In "sync" mode we don't want to parse the DAGs until we
  523. # are told to (as that would open another connection to the
  524. # SQLite DB which isn't a good practice
  525. # This shouldn't happen, as in sync mode poll should block for
  526. # ever. Lets be defensive about that.
  527. self.log.warning(
  528. "wait() unexpectedly returned nothing ready after infinite timeout (%r)!", poll_time
  529. )
  530. continue
  531. for sentinel in ready:
  532. if sentinel is not self._direct_scheduler_conn:
  533. processor = self.waitables.get(sentinel)
  534. if processor:
  535. self._collect_results_from_processor(processor)
  536. self.waitables.pop(sentinel)
  537. self._processors.pop(processor.file_path)
  538. if self.standalone_dag_processor:
  539. for callback in DagFileProcessorManager._fetch_callbacks(
  540. max_callbacks_per_loop, self.standalone_dag_processor, self.get_dag_directory()
  541. ):
  542. self._add_callback_to_queue(callback)
  543. self._scan_stale_dags()
  544. DagWarning.purge_inactive_dag_warnings()
  545. refreshed_dag_dir = self._refresh_dag_dir()
  546. if span.is_recording():
  547. span.add_event(name="_kill_timed_out_processors")
  548. self._kill_timed_out_processors()
  549. # Generate more file paths to process if we processed all the files already. Note for this
  550. # to clear down, we must have cleared all files found from scanning the dags dir _and_ have
  551. # cleared all files added as a result of callbacks
  552. if not self._file_path_queue:
  553. self.emit_metrics()
  554. if span.is_recording():
  555. span.add_event(name="prepare_file_path_queue")
  556. self.prepare_file_path_queue()
  557. # if new files found in dag dir, add them
  558. elif refreshed_dag_dir:
  559. if span.is_recording():
  560. span.add_event(name="add_new_file_path_to_queue")
  561. self.add_new_file_path_to_queue()
  562. self._refresh_requested_filelocs()
  563. if span.is_recording():
  564. span.add_event(name="start_new_processes")
  565. self.start_new_processes()
  566. # Update number of loop iteration.
  567. self._num_run += 1
  568. if not self._async_mode:
  569. self.log.debug("Waiting for processors to finish since we're using sqlite")
  570. # Wait until the running DAG processors are finished before
  571. # sending a DagParsingStat message back. This means the Agent
  572. # can tell we've got to the end of this iteration when it sees
  573. # this type of message
  574. self.wait_until_finished()
  575. # Collect anything else that has finished, but don't kick off any more processors
  576. if span.is_recording():
  577. span.add_event(name="collect_results")
  578. self.collect_results()
  579. if span.is_recording():
  580. span.add_event(name="print_stat")
  581. self._print_stat()
  582. all_files_processed = all(self.get_last_finish_time(x) is not None for x in self.file_paths)
  583. max_runs_reached = self.max_runs_reached()
  584. try:
  585. if self._direct_scheduler_conn:
  586. self._direct_scheduler_conn.send(
  587. DagParsingStat(
  588. max_runs_reached,
  589. all_files_processed,
  590. )
  591. )
  592. except BlockingIOError:
  593. # Try again next time around the loop!
  594. # It is better to fail, than it is deadlock. This should
  595. # "almost never happen" since the DagParsingStat object is
  596. # small, and in async mode this stat is not actually _required_
  597. # for normal operation (It only drives "max runs")
  598. self.log.debug("BlockingIOError received trying to send DagParsingStat, ignoring")
  599. if max_runs_reached:
  600. self.log.info(
  601. "Exiting dag parsing loop as all files have been processed %s times", self._max_runs
  602. )
  603. if span.is_recording():
  604. span.add_event(
  605. name="info",
  606. attributes={
  607. "message": "Exiting dag parsing loop as all files have been processed {self._max_runs} times"
  608. },
  609. )
  610. break
  611. if self._async_mode:
  612. loop_duration = time.monotonic() - loop_start_time
  613. if loop_duration < 1:
  614. poll_time = 1 - loop_duration
  615. else:
  616. poll_time = 0.0
  617. @classmethod
  618. @internal_api_call
  619. @provide_session
  620. def _fetch_callbacks(
  621. cls,
  622. max_callbacks: int,
  623. standalone_dag_processor: bool,
  624. dag_directory: str,
  625. session: Session = NEW_SESSION,
  626. ) -> list[CallbackRequest]:
  627. return cls._fetch_callbacks_with_retries(
  628. max_callbacks, standalone_dag_processor, dag_directory, session
  629. )
  630. @classmethod
  631. @retry_db_transaction
  632. def _fetch_callbacks_with_retries(
  633. cls, max_callbacks: int, standalone_dag_processor: bool, dag_directory: str, session: Session
  634. ) -> list[CallbackRequest]:
  635. """Fetch callbacks from database and add them to the internal queue for execution."""
  636. cls.logger().debug("Fetching callbacks from the database.")
  637. callback_queue: list[CallbackRequest] = []
  638. with prohibit_commit(session) as guard:
  639. query = select(DbCallbackRequest)
  640. if standalone_dag_processor:
  641. query = query.where(
  642. DbCallbackRequest.processor_subdir == dag_directory,
  643. )
  644. query = query.order_by(DbCallbackRequest.priority_weight.asc()).limit(max_callbacks)
  645. query = with_row_locks(query, of=DbCallbackRequest, session=session, skip_locked=True)
  646. callbacks = session.scalars(query)
  647. for callback in callbacks:
  648. try:
  649. callback_queue.append(callback.get_callback_request())
  650. session.delete(callback)
  651. except Exception as e:
  652. cls.logger().warning("Error adding callback for execution: %s, %s", callback, e)
  653. guard.commit()
  654. return callback_queue
  655. def _add_callback_to_queue(self, request: CallbackRequest):
  656. # requests are sent by dag processors. SLAs exist per-dag, but can be generated once per SLA-enabled
  657. # task in the dag. If treated like other callbacks, SLAs can cause feedback where a SLA arrives,
  658. # goes to the front of the queue, gets processed, triggers more SLAs from the same DAG, which go to
  659. # the front of the queue, and we never get round to picking stuff off the back of the queue
  660. if isinstance(request, SlaCallbackRequest):
  661. if request in self._callback_to_execute[request.full_filepath]:
  662. self.log.debug("Skipping already queued SlaCallbackRequest")
  663. return
  664. # not already queued, queue the callback
  665. # do NOT add the file of this SLA to self._file_path_queue. SLAs can arrive so rapidly that
  666. # they keep adding to the file queue and never letting it drain. This in turn prevents us from
  667. # ever rescanning the dags folder for changes to existing dags. We simply store the callback, and
  668. # periodically, when self._file_path_queue is drained, we rescan and re-queue all DAG files.
  669. # The SLAs will be picked up then. It means a delay in reacting to the SLAs (as controlled by the
  670. # min_file_process_interval config) but stops SLAs from DoS'ing the queue.
  671. self.log.debug("Queuing SlaCallbackRequest for %s", request.dag_id)
  672. self._callback_to_execute[request.full_filepath].append(request)
  673. Stats.incr("dag_processing.sla_callback_count")
  674. # Other callbacks have a higher priority over DAG Run scheduling, so those callbacks gazump, even if
  675. # already in the file path queue
  676. else:
  677. self.log.debug("Queuing %s CallbackRequest: %s", type(request).__name__, request)
  678. self._callback_to_execute[request.full_filepath].append(request)
  679. if request.full_filepath in self._file_path_queue:
  680. # Remove file paths matching request.full_filepath from self._file_path_queue
  681. # Since we are already going to use that filepath to run callback,
  682. # there is no need to have same file path again in the queue
  683. self._file_path_queue = deque(
  684. file_path for file_path in self._file_path_queue if file_path != request.full_filepath
  685. )
  686. self._add_paths_to_queue([request.full_filepath], True)
  687. Stats.incr("dag_processing.other_callback_count")
  688. def _refresh_requested_filelocs(self) -> None:
  689. """Refresh filepaths from dag dir as requested by users via APIs."""
  690. # Get values from DB table
  691. filelocs = DagFileProcessorManager._get_priority_filelocs()
  692. for fileloc in filelocs:
  693. # Try removing the fileloc if already present
  694. try:
  695. self._file_path_queue.remove(fileloc)
  696. except ValueError:
  697. pass
  698. # enqueue fileloc to the start of the queue.
  699. self._file_path_queue.appendleft(fileloc)
  700. @classmethod
  701. @internal_api_call
  702. @provide_session
  703. def _get_priority_filelocs(cls, session: Session = NEW_SESSION):
  704. """Get filelocs from DB table."""
  705. filelocs: list[str] = []
  706. requests = session.scalars(select(DagPriorityParsingRequest))
  707. for request in requests:
  708. filelocs.append(request.fileloc)
  709. session.delete(request)
  710. return filelocs
  711. def _refresh_dag_dir(self) -> bool:
  712. """Refresh file paths from dag dir if we haven't done it for too long."""
  713. now = timezone.utcnow()
  714. elapsed_time_since_refresh = (now - self.last_dag_dir_refresh_time).total_seconds()
  715. if elapsed_time_since_refresh > self.dag_dir_list_interval:
  716. # Build up a list of Python files that could contain DAGs
  717. self.log.info("Searching for files in %s", self._dag_directory)
  718. self._file_paths = list_py_file_paths(self._dag_directory)
  719. self.last_dag_dir_refresh_time = now
  720. self.log.info("There are %s files in %s", len(self._file_paths), self._dag_directory)
  721. self.set_file_paths(self._file_paths)
  722. try:
  723. self.log.debug("Removing old import errors")
  724. DagFileProcessorManager.clear_nonexistent_import_errors(
  725. file_paths=self._file_paths, processor_subdir=self.get_dag_directory()
  726. )
  727. except Exception:
  728. self.log.exception("Error removing old import errors")
  729. def _iter_dag_filelocs(fileloc: str) -> Iterator[str]:
  730. """
  731. Get "full" paths to DAGs if inside ZIP files.
  732. This is the format used by the remove/delete functions.
  733. """
  734. if fileloc.endswith(".py") or not zipfile.is_zipfile(fileloc):
  735. yield fileloc
  736. return
  737. try:
  738. with zipfile.ZipFile(fileloc) as z:
  739. for info in z.infolist():
  740. if might_contain_dag(info.filename, True, z):
  741. yield os.path.join(fileloc, info.filename)
  742. except zipfile.BadZipFile:
  743. self.log.exception("There was an error accessing ZIP file %s %s", fileloc)
  744. dag_filelocs = {full_loc for path in self._file_paths for full_loc in _iter_dag_filelocs(path)}
  745. from airflow.models.dagcode import DagCode
  746. SerializedDagModel.remove_deleted_dags(
  747. alive_dag_filelocs=dag_filelocs,
  748. processor_subdir=self.get_dag_directory(),
  749. )
  750. DagModel.deactivate_deleted_dags(
  751. dag_filelocs,
  752. processor_subdir=self.get_dag_directory(),
  753. )
  754. DagCode.remove_deleted_code(
  755. dag_filelocs,
  756. processor_subdir=self.get_dag_directory(),
  757. )
  758. return True
  759. return False
  760. def _print_stat(self):
  761. """Occasionally print out stats about how fast the files are getting processed."""
  762. if 0 < self.print_stats_interval < time.monotonic() - self.last_stat_print_time:
  763. if self._file_paths:
  764. self._log_file_processing_stats(self._file_paths)
  765. self.last_stat_print_time = time.monotonic()
  766. @staticmethod
  767. @internal_api_call
  768. @provide_session
  769. def clear_nonexistent_import_errors(
  770. file_paths: list[str] | None, processor_subdir: str | None, session=NEW_SESSION
  771. ):
  772. """
  773. Clear import errors for files that no longer exist.
  774. :param file_paths: list of paths to DAG definition files
  775. :param session: session for ORM operations
  776. """
  777. query = delete(ParseImportError)
  778. if file_paths:
  779. query = query.where(
  780. ~ParseImportError.filename.in_(file_paths),
  781. ParseImportError.processor_subdir == processor_subdir,
  782. )
  783. session.execute(query.execution_options(synchronize_session="fetch"))
  784. session.commit()
  785. def _log_file_processing_stats(self, known_file_paths):
  786. """
  787. Print out stats about how files are getting processed.
  788. :param known_file_paths: a list of file paths that may contain Airflow
  789. DAG definitions
  790. :return: None
  791. """
  792. # File Path: Path to the file containing the DAG definition
  793. # PID: PID associated with the process that's processing the file. May
  794. # be empty.
  795. # Runtime: If the process is currently running, how long it's been
  796. # running for in seconds.
  797. # Last Runtime: If the process ran before, how long did it take to
  798. # finish in seconds
  799. # Last Run: When the file finished processing in the previous run.
  800. # Last # of DB Queries: The number of queries performed to the
  801. # Airflow database during last parsing of the file.
  802. headers = [
  803. "File Path",
  804. "PID",
  805. "Runtime",
  806. "# DAGs",
  807. "# Errors",
  808. "Last Runtime",
  809. "Last Run",
  810. "Last # of DB Queries",
  811. ]
  812. rows = []
  813. now = timezone.utcnow()
  814. for file_path in known_file_paths:
  815. last_runtime = self.get_last_runtime(file_path)
  816. num_dags = self.get_last_dag_count(file_path)
  817. num_errors = self.get_last_error_count(file_path)
  818. file_name = Path(file_path).stem
  819. processor_pid = self.get_pid(file_path)
  820. processor_start_time = self.get_start_time(file_path)
  821. runtime = (now - processor_start_time) if processor_start_time else None
  822. last_run = self.get_last_finish_time(file_path)
  823. if last_run:
  824. seconds_ago = (now - last_run).total_seconds()
  825. Stats.gauge(f"dag_processing.last_run.seconds_ago.{file_name}", seconds_ago)
  826. last_num_of_db_queries = self.get_last_num_of_db_queries(file_path)
  827. Stats.gauge(f"dag_processing.last_num_of_db_queries.{file_name}", last_num_of_db_queries)
  828. rows.append(
  829. (
  830. file_path,
  831. processor_pid,
  832. runtime,
  833. num_dags,
  834. num_errors,
  835. last_runtime,
  836. last_run,
  837. last_num_of_db_queries,
  838. )
  839. )
  840. # Sort by longest last runtime. (Can't sort None values in python3)
  841. rows.sort(key=lambda x: x[5] or 0.0, reverse=True)
  842. formatted_rows = []
  843. for (
  844. file_path,
  845. pid,
  846. runtime,
  847. num_dags,
  848. num_errors,
  849. last_runtime,
  850. last_run,
  851. last_num_of_db_queries,
  852. ) in rows:
  853. formatted_rows.append(
  854. (
  855. file_path,
  856. pid,
  857. f"{runtime.total_seconds():.2f}s" if runtime else None,
  858. num_dags,
  859. num_errors,
  860. f"{last_runtime:.2f}s" if last_runtime else None,
  861. last_run.strftime("%Y-%m-%dT%H:%M:%S") if last_run else None,
  862. last_num_of_db_queries,
  863. )
  864. )
  865. log_str = (
  866. "\n"
  867. + "=" * 80
  868. + "\n"
  869. + "DAG File Processing Stats\n\n"
  870. + tabulate(formatted_rows, headers=headers)
  871. + "\n"
  872. + "=" * 80
  873. )
  874. self.log.info(log_str)
  875. def get_pid(self, file_path) -> int | None:
  876. """
  877. Retrieve the PID of the process processing the given file or None if the file is not being processed.
  878. :param file_path: the path to the file that's being processed.
  879. """
  880. if file_path in self._processors:
  881. return self._processors[file_path].pid
  882. return None
  883. def get_all_pids(self) -> list[int]:
  884. """
  885. Get all pids.
  886. :return: a list of the PIDs for the processors that are running
  887. """
  888. return [x.pid for x in self._processors.values()]
  889. def get_last_runtime(self, file_path) -> float | None:
  890. """
  891. Retrieve the last processing time of a specific path.
  892. :param file_path: the path to the file that was processed
  893. :return: the runtime (in seconds) of the process of the last run, or
  894. None if the file was never processed.
  895. """
  896. stat = self._file_stats.get(file_path)
  897. return stat.last_duration.total_seconds() if stat and stat.last_duration else None
  898. def get_last_dag_count(self, file_path) -> int | None:
  899. """
  900. Retrieve the total DAG count at a specific path.
  901. :param file_path: the path to the file that was processed
  902. :return: the number of dags loaded from that file, or None if the file was never processed.
  903. """
  904. stat = self._file_stats.get(file_path)
  905. return stat.num_dags if stat else None
  906. def get_last_error_count(self, file_path) -> int | None:
  907. """
  908. Retrieve the total number of errors from processing a specific path.
  909. :param file_path: the path to the file that was processed
  910. :return: the number of import errors from processing, or None if the file was never processed.
  911. """
  912. stat = self._file_stats.get(file_path)
  913. return stat.import_errors if stat else None
  914. def get_last_num_of_db_queries(self, file_path) -> int | None:
  915. """
  916. Retrieve the number of queries performed to the Airflow database during last parsing of the file.
  917. :param file_path: the path to the file that was processed
  918. :return: the number of queries performed to the Airflow database during last parsing of the file,
  919. or None if the file was never processed.
  920. """
  921. stat = self._file_stats.get(file_path)
  922. return stat.last_num_of_db_queries if stat else None
  923. def get_last_finish_time(self, file_path) -> datetime | None:
  924. """
  925. Retrieve the last completion time for processing a specific path.
  926. :param file_path: the path to the file that was processed
  927. :return: the finish time of the process of the last run, or None if the file was never processed.
  928. """
  929. stat = self._file_stats.get(file_path)
  930. return stat.last_finish_time if stat else None
  931. def get_start_time(self, file_path) -> datetime | None:
  932. """
  933. Retrieve the last start time for processing a specific path.
  934. :param file_path: the path to the file that's being processed
  935. :return: the start time of the process that's processing the
  936. specified file or None if the file is not currently being processed.
  937. """
  938. if file_path in self._processors:
  939. return self._processors[file_path].start_time
  940. return None
  941. def get_run_count(self, file_path) -> int:
  942. """
  943. Return the number of times the given file has been parsed.
  944. :param file_path: the path to the file that's being processed.
  945. """
  946. stat = self._file_stats.get(file_path)
  947. return stat.run_count if stat else 0
  948. def get_dag_directory(self) -> str:
  949. """Return the dag_director as a string."""
  950. if isinstance(self._dag_directory, Path):
  951. return str(self._dag_directory.resolve())
  952. else:
  953. return str(self._dag_directory)
  954. def set_file_paths(self, new_file_paths):
  955. """
  956. Update this with a new set of paths to DAG definition files.
  957. :param new_file_paths: list of paths to DAG definition files
  958. :return: None
  959. """
  960. self._file_paths = new_file_paths
  961. # clean up the queues; remove anything queued which no longer in the list, including callbacks
  962. self._file_path_queue = deque(x for x in self._file_path_queue if x in new_file_paths)
  963. Stats.gauge("dag_processing.file_path_queue_size", len(self._file_path_queue))
  964. callback_paths_to_del = [x for x in self._callback_to_execute if x not in new_file_paths]
  965. for path_to_del in callback_paths_to_del:
  966. del self._callback_to_execute[path_to_del]
  967. # Stop processors that are working on deleted files
  968. filtered_processors = {}
  969. for file_path, processor in self._processors.items():
  970. if file_path in new_file_paths:
  971. filtered_processors[file_path] = processor
  972. else:
  973. self.log.warning("Stopping processor for %s", file_path)
  974. Stats.decr("dag_processing.processes", tags={"file_path": file_path, "action": "stop"})
  975. processor.terminate()
  976. self._file_stats.pop(file_path)
  977. to_remove = set(self._file_stats).difference(self._file_paths)
  978. for key in to_remove:
  979. # Remove the stats for any dag files that don't exist anymore
  980. del self._file_stats[key]
  981. self._processors = filtered_processors
  982. def wait_until_finished(self):
  983. """Sleeps until all the processors are done."""
  984. for processor in self._processors.values():
  985. while not processor.done:
  986. time.sleep(0.1)
  987. def _collect_results_from_processor(self, processor) -> None:
  988. self.log.debug("Processor for %s finished", processor.file_path)
  989. Stats.decr("dag_processing.processes", tags={"file_path": processor.file_path, "action": "finish"})
  990. last_finish_time = timezone.utcnow()
  991. if processor.result is not None:
  992. num_dags, count_import_errors, last_num_of_db_queries = processor.result
  993. else:
  994. self.log.error(
  995. "Processor for %s exited with return code %s.", processor.file_path, processor.exit_code
  996. )
  997. count_import_errors = -1
  998. num_dags = 0
  999. last_num_of_db_queries = 0
  1000. last_duration = last_finish_time - processor.start_time
  1001. stat = DagFileStat(
  1002. num_dags=num_dags,
  1003. import_errors=count_import_errors,
  1004. last_finish_time=last_finish_time,
  1005. last_duration=last_duration,
  1006. run_count=self.get_run_count(processor.file_path) + 1,
  1007. last_num_of_db_queries=last_num_of_db_queries,
  1008. )
  1009. self._file_stats[processor.file_path] = stat
  1010. file_name = Path(processor.file_path).stem
  1011. """crude exposure of instrumentation code which may need to be furnished"""
  1012. span = Trace.get_tracer("DagFileProcessorManager").start_span(
  1013. "dag_processing", start_time=datetime_to_nano(processor.start_time)
  1014. )
  1015. span.set_attribute("file_path", processor.file_path)
  1016. span.set_attribute("run_count", self.get_run_count(processor.file_path) + 1)
  1017. if processor.result is None:
  1018. span.set_attribute("error", True)
  1019. span.set_attribute("processor.exit_code", processor.exit_code)
  1020. else:
  1021. span.set_attribute("num_dags", num_dags)
  1022. span.set_attribute("import_errors", count_import_errors)
  1023. if count_import_errors > 0:
  1024. span.set_attribute("error", True)
  1025. span.end(end_time=datetime_to_nano(last_finish_time))
  1026. Stats.timing(f"dag_processing.last_duration.{file_name}", last_duration)
  1027. Stats.timing("dag_processing.last_duration", last_duration, tags={"file_name": file_name})
  1028. def collect_results(self) -> None:
  1029. """Collect the result from any finished DAG processors."""
  1030. ready = multiprocessing.connection.wait(
  1031. self.waitables.keys() - [self._direct_scheduler_conn], timeout=0
  1032. )
  1033. for sentinel in ready:
  1034. if sentinel is not self._direct_scheduler_conn:
  1035. processor = cast(DagFileProcessorProcess, self.waitables[sentinel])
  1036. self.waitables.pop(processor.waitable_handle)
  1037. self._processors.pop(processor.file_path)
  1038. self._collect_results_from_processor(processor)
  1039. self.log.debug("%s/%s DAG parsing processes running", len(self._processors), self._parallelism)
  1040. self.log.debug("%s file paths queued for processing", len(self._file_path_queue))
  1041. @staticmethod
  1042. def _create_process(file_path, pickle_dags, dag_ids, dag_directory, callback_requests):
  1043. """Create DagFileProcessorProcess instance."""
  1044. return DagFileProcessorProcess(
  1045. file_path=file_path,
  1046. pickle_dags=pickle_dags,
  1047. dag_ids=dag_ids,
  1048. dag_directory=dag_directory,
  1049. callback_requests=callback_requests,
  1050. )
  1051. @span
  1052. def start_new_processes(self):
  1053. """Start more processors if we have enough slots and files to process."""
  1054. # initialize cache to mutualize calls to Variable.get in DAGs
  1055. # needs to be done before this process is forked to create the DAG parsing processes.
  1056. SecretCache.init()
  1057. while self._parallelism > len(self._processors) and self._file_path_queue:
  1058. file_path = self._file_path_queue.popleft()
  1059. # Stop creating duplicate processor i.e. processor with the same filepath
  1060. if file_path in self._processors:
  1061. continue
  1062. callback_to_execute_for_file = self._callback_to_execute[file_path]
  1063. processor = self._create_process(
  1064. file_path,
  1065. self._pickle_dags,
  1066. self._dag_ids,
  1067. self.get_dag_directory(),
  1068. callback_to_execute_for_file,
  1069. )
  1070. del self._callback_to_execute[file_path]
  1071. Stats.incr("dag_processing.processes", tags={"file_path": file_path, "action": "start"})
  1072. span = Trace.get_current_span()
  1073. span.set_attribute("category", "processing")
  1074. processor.start()
  1075. self.log.debug("Started a process (PID: %s) to generate tasks for %s", processor.pid, file_path)
  1076. if span.is_recording():
  1077. span.add_event(
  1078. name="dag_processing processor started",
  1079. attributes={"file_path": file_path, "pid": processor.pid},
  1080. )
  1081. self._processors[file_path] = processor
  1082. self.waitables[processor.waitable_handle] = processor
  1083. Stats.gauge("dag_processing.file_path_queue_size", len(self._file_path_queue))
  1084. @span
  1085. def add_new_file_path_to_queue(self):
  1086. for file_path in self.file_paths:
  1087. if file_path not in self._file_stats:
  1088. # We found new file after refreshing dir. add to parsing queue at start
  1089. self.log.info("Adding new file %s to parsing queue", file_path)
  1090. self._file_stats[file_path] = DagFileProcessorManager.DEFAULT_FILE_STAT
  1091. self._file_path_queue.appendleft(file_path)
  1092. span = Trace.get_current_span()
  1093. if span.is_recording():
  1094. span.add_event(
  1095. name="adding new file to parsing queue", attributes={"file_path": file_path}
  1096. )
  1097. def prepare_file_path_queue(self):
  1098. """
  1099. Scan dags dir to generate more file paths to process.
  1100. Note this method is only called when the file path queue is empty
  1101. """
  1102. self._parsing_start_time = time.perf_counter()
  1103. # If the file path is already being processed, or if a file was
  1104. # processed recently, wait until the next batch
  1105. file_paths_in_progress = set(self._processors)
  1106. now = timezone.utcnow()
  1107. # Sort the file paths by the parsing order mode
  1108. list_mode = conf.get("scheduler", "file_parsing_sort_mode")
  1109. files_with_mtime = {}
  1110. file_paths = []
  1111. is_mtime_mode = list_mode == "modified_time"
  1112. file_paths_recently_processed = []
  1113. file_paths_to_stop_watching = set()
  1114. for file_path in self._file_paths:
  1115. if is_mtime_mode:
  1116. try:
  1117. files_with_mtime[file_path] = os.path.getmtime(file_path)
  1118. except FileNotFoundError:
  1119. self.log.warning("Skipping processing of missing file: %s", file_path)
  1120. self._file_stats.pop(file_path, None)
  1121. file_paths_to_stop_watching.add(file_path)
  1122. continue
  1123. file_modified_time = datetime.fromtimestamp(files_with_mtime[file_path], tz=timezone.utc)
  1124. else:
  1125. file_paths.append(file_path)
  1126. file_modified_time = None
  1127. # Find file paths that were recently processed to exclude them
  1128. # from being added to file_path_queue
  1129. # unless they were modified recently and parsing mode is "modified_time"
  1130. # in which case we don't honor "self._file_process_interval" (min_file_process_interval)
  1131. last_finish_time = self.get_last_finish_time(file_path)
  1132. if (
  1133. last_finish_time is not None
  1134. and (now - last_finish_time).total_seconds() < self._file_process_interval
  1135. and not (is_mtime_mode and file_modified_time and (file_modified_time > last_finish_time))
  1136. ):
  1137. file_paths_recently_processed.append(file_path)
  1138. # Sort file paths via last modified time
  1139. if is_mtime_mode:
  1140. file_paths = sorted(files_with_mtime, key=files_with_mtime.get, reverse=True)
  1141. elif list_mode == "alphabetical":
  1142. file_paths.sort()
  1143. elif list_mode == "random_seeded_by_host":
  1144. # Shuffle the list seeded by hostname so multiple schedulers can work on different
  1145. # set of files. Since we set the seed, the sort order will remain same per host
  1146. random.Random(get_hostname()).shuffle(file_paths)
  1147. if file_paths_to_stop_watching:
  1148. self.set_file_paths(
  1149. [path for path in self._file_paths if path not in file_paths_to_stop_watching]
  1150. )
  1151. files_paths_at_run_limit = [
  1152. file_path for file_path, stat in self._file_stats.items() if stat.run_count == self._max_runs
  1153. ]
  1154. file_paths_to_exclude = file_paths_in_progress.union(
  1155. file_paths_recently_processed,
  1156. files_paths_at_run_limit,
  1157. )
  1158. # Do not convert the following list to set as set does not preserve the order
  1159. # and we need to maintain the order of file_paths for `[scheduler] file_parsing_sort_mode`
  1160. files_paths_to_queue = [
  1161. file_path for file_path in file_paths if file_path not in file_paths_to_exclude
  1162. ]
  1163. if self.log.isEnabledFor(logging.DEBUG):
  1164. for processor in self._processors.values():
  1165. self.log.debug(
  1166. "File path %s is still being processed (started: %s)",
  1167. processor.file_path,
  1168. processor.start_time.isoformat(),
  1169. )
  1170. self.log.debug(
  1171. "Queuing the following files for processing:\n\t%s", "\n\t".join(files_paths_to_queue)
  1172. )
  1173. for file_path in files_paths_to_queue:
  1174. self._file_stats.setdefault(file_path, DagFileProcessorManager.DEFAULT_FILE_STAT)
  1175. self._add_paths_to_queue(files_paths_to_queue, False)
  1176. Stats.incr("dag_processing.file_path_queue_update_count")
  1177. def _kill_timed_out_processors(self):
  1178. """Kill any file processors that timeout to defend against process hangs."""
  1179. now = timezone.utcnow()
  1180. processors_to_remove = []
  1181. for file_path, processor in self._processors.items():
  1182. duration = now - processor.start_time
  1183. if duration > self._processor_timeout:
  1184. self.log.error(
  1185. "Processor for %s with PID %s started at %s has timed out, killing it.",
  1186. file_path,
  1187. processor.pid,
  1188. processor.start_time.isoformat(),
  1189. )
  1190. Stats.decr("dag_processing.processes", tags={"file_path": file_path, "action": "timeout"})
  1191. Stats.incr("dag_processing.processor_timeouts", tags={"file_path": file_path})
  1192. # Deprecated; may be removed in a future Airflow release.
  1193. Stats.incr("dag_file_processor_timeouts")
  1194. processor.kill()
  1195. span = Trace.get_current_span()
  1196. span.set_attribute("category", "processing")
  1197. if span.is_recording():
  1198. span.add_event(
  1199. name="dag processing killed processor",
  1200. attributes={"file_path": file_path, "action": "timeout"},
  1201. )
  1202. # Clean up processor references
  1203. self.waitables.pop(processor.waitable_handle)
  1204. processors_to_remove.append(file_path)
  1205. stat = DagFileStat(
  1206. num_dags=0,
  1207. import_errors=1,
  1208. last_finish_time=now,
  1209. last_duration=duration,
  1210. run_count=self.get_run_count(file_path) + 1,
  1211. last_num_of_db_queries=0,
  1212. )
  1213. self._file_stats[processor.file_path] = stat
  1214. # Clean up `self._processors` after iterating over it
  1215. for proc in processors_to_remove:
  1216. self._processors.pop(proc)
  1217. def _add_paths_to_queue(self, file_paths_to_enqueue: list[str], add_at_front: bool):
  1218. """Add stuff to the back or front of the file queue, unless it's already present."""
  1219. new_file_paths = list(p for p in file_paths_to_enqueue if p not in self._file_path_queue)
  1220. if add_at_front:
  1221. self._file_path_queue.extendleft(new_file_paths)
  1222. else:
  1223. self._file_path_queue.extend(new_file_paths)
  1224. Stats.gauge("dag_processing.file_path_queue_size", len(self._file_path_queue))
  1225. def max_runs_reached(self):
  1226. """:return: whether all file paths have been processed max_runs times."""
  1227. if self._max_runs == -1: # Unlimited runs.
  1228. return False
  1229. for stat in self._file_stats.values():
  1230. if stat.run_count < self._max_runs:
  1231. return False
  1232. if self._num_run < self._max_runs:
  1233. return False
  1234. return True
  1235. def terminate(self):
  1236. """Stop all running processors."""
  1237. for processor in self._processors.values():
  1238. Stats.decr(
  1239. "dag_processing.processes", tags={"file_path": processor.file_path, "action": "terminate"}
  1240. )
  1241. processor.terminate()
  1242. def end(self):
  1243. """Kill all child processes on exit since we don't want to leave them as orphaned."""
  1244. pids_to_kill = self.get_all_pids()
  1245. if pids_to_kill:
  1246. kill_child_processes_by_pids(pids_to_kill)
  1247. def emit_metrics(self):
  1248. """
  1249. Emit metrics about dag parsing summary.
  1250. This is called once every time around the parsing "loop" - i.e. after
  1251. all files have been parsed.
  1252. """
  1253. with Trace.start_span(span_name="emit_metrics", component="DagFileProcessorManager") as span:
  1254. parse_time = time.perf_counter() - self._parsing_start_time
  1255. Stats.gauge("dag_processing.total_parse_time", parse_time)
  1256. Stats.gauge("dagbag_size", sum(stat.num_dags for stat in self._file_stats.values()))
  1257. Stats.gauge(
  1258. "dag_processing.import_errors", sum(stat.import_errors for stat in self._file_stats.values())
  1259. )
  1260. span.set_attribute("total_parse_time", parse_time)
  1261. span.set_attribute("dag_bag_size", sum(stat.num_dags for stat in self._file_stats.values()))
  1262. span.set_attribute("import_errors", sum(stat.import_errors for stat in self._file_stats.values()))
  1263. @property
  1264. def file_paths(self):
  1265. return self._file_paths
  1266. def reload_configuration_for_dag_processing():
  1267. # Reload configurations and settings to avoid collision with parent process.
  1268. # Because this process may need custom configurations that cannot be shared,
  1269. # e.g. RotatingFileHandler. And it can cause connection corruption if we
  1270. # do not recreate the SQLA connection pool.
  1271. os.environ["CONFIG_PROCESSOR_MANAGER_LOGGER"] = "True"
  1272. os.environ["AIRFLOW__LOGGING__COLORED_CONSOLE_LOG"] = "False"
  1273. # Replicating the behavior of how logging module was loaded
  1274. # in logging_config.py
  1275. # TODO: This reloading should be removed when we fix our logging behaviour
  1276. # In case of "spawn" method of starting processes for multiprocessing, reinitializing of the
  1277. # SQLAlchemy engine causes extremely unexpected behaviour of messing with objects already loaded
  1278. # in a parent process (likely via resources shared in memory by the ORM libraries).
  1279. # This caused flaky tests in our CI for many months and has been discovered while
  1280. # iterating on https://github.com/apache/airflow/pull/19860
  1281. # The issue that describes the problem and possible remediation is
  1282. # at https://github.com/apache/airflow/issues/19934
  1283. importlib.reload(import_module(airflow.settings.LOGGING_CLASS_PATH.rsplit(".", 1)[0])) # type: ignore
  1284. importlib.reload(airflow.settings)
  1285. airflow.settings.initialize()
  1286. del os.environ["CONFIG_PROCESSOR_MANAGER_LOGGER"]