python_virtualenv.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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. """Utilities for creating a virtual environment."""
  19. from __future__ import annotations
  20. import os
  21. import sys
  22. import warnings
  23. from pathlib import Path
  24. import jinja2
  25. from jinja2 import select_autoescape
  26. from airflow.utils.decorators import remove_task_decorator as _remove_task_decorator
  27. from airflow.utils.process_utils import execute_in_subprocess
  28. def _generate_virtualenv_cmd(tmp_dir: str, python_bin: str, system_site_packages: bool) -> list[str]:
  29. cmd = [sys.executable, "-m", "virtualenv", tmp_dir]
  30. if system_site_packages:
  31. cmd.append("--system-site-packages")
  32. if python_bin is not None:
  33. cmd.append(f"--python={python_bin}")
  34. return cmd
  35. def _generate_pip_install_cmd_from_file(
  36. tmp_dir: str, requirements_file_path: str, pip_install_options: list[str]
  37. ) -> list[str]:
  38. return [f"{tmp_dir}/bin/pip", "install", *pip_install_options, "-r", requirements_file_path]
  39. def _generate_pip_install_cmd_from_list(
  40. tmp_dir: str, requirements: list[str], pip_install_options: list[str]
  41. ) -> list[str]:
  42. return [f"{tmp_dir}/bin/pip", "install", *pip_install_options, *requirements]
  43. def _generate_pip_conf(conf_file: Path, index_urls: list[str]) -> None:
  44. if index_urls:
  45. pip_conf_options = f"index-url = {index_urls[0]}"
  46. if len(index_urls) > 1:
  47. pip_conf_options += f"\nextra-index-url = {' '.join(x for x in index_urls[1:])}"
  48. else:
  49. pip_conf_options = "no-index = true"
  50. conf_file.write_text(f"[global]\n{pip_conf_options}")
  51. def remove_task_decorator(python_source: str, task_decorator_name: str) -> str:
  52. warnings.warn(
  53. "Import remove_task_decorator from airflow.utils.decorators instead",
  54. DeprecationWarning,
  55. stacklevel=2,
  56. )
  57. return _remove_task_decorator(python_source, task_decorator_name)
  58. def prepare_virtualenv(
  59. venv_directory: str,
  60. python_bin: str,
  61. system_site_packages: bool,
  62. requirements: list[str] | None = None,
  63. requirements_file_path: str | None = None,
  64. pip_install_options: list[str] | None = None,
  65. index_urls: list[str] | None = None,
  66. ) -> str:
  67. """
  68. Create a virtual environment and install the additional python packages.
  69. :param venv_directory: The path for directory where the environment will be created.
  70. :param python_bin: Path to the Python executable.
  71. :param system_site_packages: Whether to include system_site_packages in your virtualenv.
  72. See virtualenv documentation for more information.
  73. :param requirements: List of additional python packages.
  74. :param requirements_file_path: Path to the ``requirements.txt`` file.
  75. :param pip_install_options: a list of pip install options when installing requirements
  76. See 'pip install -h' for available options
  77. :param index_urls: an optional list of index urls to load Python packages from.
  78. If not provided the system pip conf will be used to source packages from.
  79. :return: Path to a binary file with Python in a virtual environment.
  80. """
  81. if pip_install_options is None:
  82. pip_install_options = []
  83. if index_urls is not None:
  84. _generate_pip_conf(Path(venv_directory) / "pip.conf", index_urls)
  85. virtualenv_cmd = _generate_virtualenv_cmd(venv_directory, python_bin, system_site_packages)
  86. execute_in_subprocess(virtualenv_cmd)
  87. if requirements is not None and requirements_file_path is not None:
  88. raise ValueError("Either requirements OR requirements_file_path has to be passed, but not both")
  89. pip_cmd = None
  90. if requirements is not None and len(requirements) != 0:
  91. pip_cmd = _generate_pip_install_cmd_from_list(venv_directory, requirements, pip_install_options)
  92. if requirements_file_path is not None and requirements_file_path:
  93. pip_cmd = _generate_pip_install_cmd_from_file(
  94. venv_directory, requirements_file_path, pip_install_options
  95. )
  96. if pip_cmd:
  97. execute_in_subprocess(pip_cmd)
  98. return f"{venv_directory}/bin/python"
  99. def write_python_script(
  100. jinja_context: dict,
  101. filename: str,
  102. render_template_as_native_obj: bool = False,
  103. ):
  104. """
  105. Render the python script to a file to execute in the virtual environment.
  106. :param jinja_context: The jinja context variables to unpack and replace with its placeholders in the
  107. template file.
  108. :param filename: The name of the file to dump the rendered script to.
  109. :param render_template_as_native_obj: If ``True``, rendered Jinja template would be converted
  110. to a native Python object
  111. """
  112. template_loader = jinja2.FileSystemLoader(searchpath=os.path.dirname(__file__))
  113. template_env: jinja2.Environment
  114. if render_template_as_native_obj:
  115. template_env = jinja2.nativetypes.NativeEnvironment(
  116. loader=template_loader, undefined=jinja2.StrictUndefined
  117. )
  118. else:
  119. template_env = jinja2.Environment(
  120. loader=template_loader,
  121. undefined=jinja2.StrictUndefined,
  122. autoescape=select_autoescape(["html", "xml"]),
  123. )
  124. template = template_env.get_template("python_virtualenv_script.jinja2")
  125. template.stream(**jinja_context).dump(filename)