mixins.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. from __future__ import annotations
  19. import multiprocessing
  20. import multiprocessing.context
  21. import typing
  22. from airflow.configuration import conf
  23. if typing.TYPE_CHECKING:
  24. from airflow.models.operator import Operator
  25. from airflow.utils.context import Context
  26. class MultiprocessingStartMethodMixin:
  27. """Convenience class to add support for different types of multiprocessing."""
  28. def _get_multiprocessing_start_method(self) -> str:
  29. """
  30. Determine method of creating new processes.
  31. Checks if the mp_start_method is set in configs, else, it uses the OS default.
  32. """
  33. if conf.has_option("core", "mp_start_method"):
  34. return conf.get_mandatory_value("core", "mp_start_method")
  35. method = multiprocessing.get_start_method()
  36. if not method:
  37. raise ValueError("Failed to determine start method")
  38. return method
  39. def _get_multiprocessing_context(self) -> multiprocessing.context.DefaultContext:
  40. mp_start_method = self._get_multiprocessing_start_method()
  41. return multiprocessing.get_context(mp_start_method) # type: ignore
  42. class ResolveMixin:
  43. """A runtime-resolved value."""
  44. def iter_references(self) -> typing.Iterable[tuple[Operator, str]]:
  45. """
  46. Find underlying XCom references this contains.
  47. This is used by the DAG parser to recursively find task dependencies.
  48. :meta private:
  49. """
  50. raise NotImplementedError
  51. def resolve(self, context: Context, *, include_xcom: bool = True) -> typing.Any:
  52. """
  53. Resolve this value for runtime.
  54. :meta private:
  55. """
  56. raise NotImplementedError