file.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. from __future__ import annotations
  18. import asyncio
  19. import datetime
  20. import os
  21. import typing
  22. import warnings
  23. from glob import glob
  24. from typing import Any
  25. from airflow.triggers.base import BaseTrigger, TriggerEvent
  26. class FileTrigger(BaseTrigger):
  27. """
  28. A trigger that fires exactly once after it finds the requested file or folder.
  29. :param filepath: File or folder name (relative to the base path set within the connection), can
  30. be a glob.
  31. :param recursive: when set to ``True``, enables recursive directory matching behavior of
  32. ``**`` in glob filepath parameter. Defaults to ``False``.
  33. :param poke_interval: Time that the job should wait in between each try
  34. """
  35. def __init__(
  36. self,
  37. filepath: str,
  38. recursive: bool = False,
  39. poke_interval: float = 5.0,
  40. **kwargs,
  41. ):
  42. super().__init__()
  43. self.filepath = filepath
  44. self.recursive = recursive
  45. if kwargs.get("poll_interval") is not None:
  46. warnings.warn(
  47. "`poll_interval` has been deprecated and will be removed in future."
  48. "Please use `poke_interval` instead.",
  49. DeprecationWarning,
  50. stacklevel=2,
  51. )
  52. self.poke_interval: float = kwargs["poll_interval"]
  53. else:
  54. self.poke_interval = poke_interval
  55. def serialize(self) -> tuple[str, dict[str, Any]]:
  56. """Serialize FileTrigger arguments and classpath."""
  57. return (
  58. "airflow.triggers.file.FileTrigger",
  59. {
  60. "filepath": self.filepath,
  61. "recursive": self.recursive,
  62. "poke_interval": self.poke_interval,
  63. },
  64. )
  65. async def run(self) -> typing.AsyncIterator[TriggerEvent]:
  66. """Loop until the relevant files are found."""
  67. while True:
  68. for path in glob(self.filepath, recursive=self.recursive):
  69. if os.path.isfile(path):
  70. mod_time_f = os.path.getmtime(path)
  71. mod_time = datetime.datetime.fromtimestamp(mod_time_f).strftime("%Y%m%d%H%M%S")
  72. self.log.info("Found File %s last modified: %s", path, mod_time)
  73. yield TriggerEvent(True)
  74. return
  75. for _, _, files in os.walk(self.filepath):
  76. if files:
  77. yield TriggerEvent(True)
  78. return
  79. await asyncio.sleep(self.poke_interval)