core.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. import sys
  16. from collections import OrderedDict
  17. from ..utils import logging
  18. from .utils import install_deps_using_pip
  19. from .meta import get_all_repo_names, get_repo_meta
  20. from .repo import (
  21. build_repo_instance,
  22. build_repo_group_getter,
  23. build_repo_group_installer,
  24. )
  25. __all__ = [
  26. "set_parent_dirs",
  27. "setup",
  28. "wheel",
  29. "is_initialized",
  30. "initialize",
  31. "get_versions",
  32. ]
  33. def _parse_repo_deps(repos):
  34. ret = []
  35. for repo_name in repos:
  36. repo_meta = get_repo_meta(repo_name)
  37. ret.extend(_parse_repo_deps(repo_meta.get("requires", [])))
  38. ret.append(repo_name)
  39. return ret
  40. class _GlobalContext(object):
  41. REPO_PARENT_DIR = None
  42. PDX_COLLECTION_MOD = None
  43. REPOS = None
  44. @classmethod
  45. def set_parent_dirs(cls, repo_parent_dir, pdx_collection_mod):
  46. """set_parent_dirs"""
  47. cls.REPO_PARENT_DIR = repo_parent_dir
  48. cls.PDX_COLLECTION_MOD = pdx_collection_mod
  49. @classmethod
  50. def build_repo_instance(cls, repo_name):
  51. """build_repo_instance"""
  52. return build_repo_instance(
  53. repo_name, cls.REPO_PARENT_DIR, cls.PDX_COLLECTION_MOD
  54. )
  55. @classmethod
  56. def is_initialized(cls):
  57. """is_initialized"""
  58. return cls.REPOS is not None
  59. @classmethod
  60. def initialize(cls):
  61. """initialize"""
  62. cls.REPOS = []
  63. @classmethod
  64. def add_repo(cls, repo):
  65. """add_repo"""
  66. if not cls.is_initialized():
  67. cls.initialize()
  68. cls.REPOS.append(repo)
  69. @classmethod
  70. def add_repos(cls, repos):
  71. """add_repos"""
  72. if len(repos) == 0 and not cls.is_initialized():
  73. cls.initialize()
  74. for repo in repos:
  75. cls.add_repo(repo)
  76. set_parent_dirs = _GlobalContext.set_parent_dirs
  77. is_initialized = _GlobalContext.is_initialized
  78. def setup(
  79. repo_names,
  80. no_deps=False,
  81. constraints=None,
  82. platform=None,
  83. update_repos=False,
  84. use_local_repos=False,
  85. ):
  86. """setup"""
  87. if update_repos and use_local_repos:
  88. logging.error(
  89. f"The `--update_repos` and `--use_local_repos` should not be True at the same time. They are global setting for all repos. `--update_repos` means that update all repos to sync with remote, and `--use_local_repos` means that don't update when local repo is exsting."
  90. )
  91. raise Exception()
  92. repo_names = list(set(_parse_repo_deps(repo_names)))
  93. repos = []
  94. for repo_name in repo_names:
  95. repo = _GlobalContext.build_repo_instance(repo_name)
  96. repos.append(repo)
  97. changed_repos = []
  98. repos_to_get = []
  99. for repo in repos:
  100. repo_name = repo.name
  101. if repo.check_repo_exiting():
  102. if use_local_repos:
  103. # when use_local_repos has been set, it can be only assume that the local repo has changed, otherwise there is no need to specify.
  104. changed_repos.append(repo_name)
  105. logging.warning(
  106. f"We will use the existing repo of {repo.name} and the repo will be reinstall."
  107. )
  108. continue
  109. logging.warning(f"Existing of {repo.name} repo.")
  110. if update_repos:
  111. remove_existing = True
  112. else:
  113. if sys.stdin.isatty():
  114. logging.warning("Should we remove it (y/n)?")
  115. try:
  116. remove_existing = input()
  117. except EOFError:
  118. logging.warning(
  119. "Unable to read from stdin. Please set `--use_local_repos` to \
  120. True or False to apply a global setting for using exsting or re-getting repos."
  121. )
  122. raise
  123. remove_existing = remove_existing.lower() in ("y", "yes")
  124. if remove_existing:
  125. changed_repos.append(repo_name)
  126. repo.remove()
  127. logging.warning(f"Existing {repo.name} repo has been removed.")
  128. repos_to_get.append(repo)
  129. else:
  130. logging.warning(f"We will use the existing repo of {repo.name}.")
  131. else:
  132. changed_repos.append(repo)
  133. repos_to_get.append(repo)
  134. repos_to_install = []
  135. for repo in repos:
  136. repo_name = repo.name
  137. if repo.check_installation():
  138. logging.warning(f"Existing installation of {repo.name} detected.")
  139. reinstall = repo_name in changed_repos
  140. if reinstall:
  141. uninstall_existing = True
  142. else:
  143. if sys.stdin.isatty():
  144. logging.warning("Should we uninstall it (y/n)?")
  145. try:
  146. uninstall_existing = input()
  147. except EOFError:
  148. logging.warning(
  149. "Unable to read from stdin. Please set `reinstall` to \
  150. True or False to apply a global setting for reinstalling repos."
  151. )
  152. raise
  153. uninstall_existing = uninstall_existing.lower() in ("y", "yes")
  154. if uninstall_existing:
  155. repo.uninstall()
  156. repos_to_install.append(repo)
  157. else:
  158. logging.warning(
  159. f"We will use the existing installation of {repo.name}."
  160. )
  161. else:
  162. repos_to_install.append(repo)
  163. getter = build_repo_group_getter(*repos_to_get)
  164. installer = build_repo_group_installer(*repos_to_install)
  165. if len(repos_to_get) > 0:
  166. logging.info(
  167. f"Now download and update the repos: {list(repo.name for repo in repos_to_get)}."
  168. )
  169. getter.get(force=True, platform=platform)
  170. logging.info("All repos are existing.")
  171. else:
  172. logging.info("No repo need to download or update.")
  173. if not no_deps:
  174. logging.info("Dependencies are listed below:")
  175. logging.info(installer.get_deps())
  176. logging.info("Now installing the packages...")
  177. installer.install(force_reinstall=False, no_deps=no_deps, constraints=constraints)
  178. install_deps_using_pip()
  179. logging.info("All packages are installed.")
  180. def wheel(repo_names, dst_dir="./", fail_fast=False):
  181. """wheel"""
  182. for repo_name in repo_names:
  183. repo = _GlobalContext.build_repo_instance(repo_name)
  184. logging.info(f"Now building Wheel for {repo_name}...")
  185. try:
  186. tgt_dir = os.path.join(dst_dir, repo.pkg_name)
  187. if os.path.exists(tgt_dir):
  188. raise FileExistsError(f"{tgt_dir} already exists.")
  189. repo.wheel(tgt_dir)
  190. except Exception as e:
  191. logging.warning(
  192. f"Failed to build wheel for {repo_name}. We encountered the following error:\n {str(e)}\n"
  193. )
  194. if fail_fast:
  195. raise
  196. else:
  197. logging.info(f"Wheel for {repo_name} is built.\n")
  198. def initialize(repo_names=None):
  199. """initialize"""
  200. if _GlobalContext.is_initialized():
  201. raise RuntimeError(
  202. "PDX has already been initialized. Reinitialization is not supported."
  203. )
  204. if repo_names is None:
  205. try_all = True
  206. repo_names = get_all_repo_names()
  207. else:
  208. try_all = False
  209. repos = []
  210. for repo_name in repo_names:
  211. logging.debug(f"Now initializing {repo_name}...")
  212. repo = _GlobalContext.build_repo_instance(repo_name)
  213. flag = repo.initialize()
  214. if flag:
  215. logging.debug(f"{repo_name} is initialized.")
  216. repos.append(repo)
  217. else:
  218. if try_all:
  219. logging.debug(
  220. f"Failed to initialize {repo_name}. Please make sure {repo_name} is properly installed."
  221. )
  222. else:
  223. pass
  224. _GlobalContext.add_repos(repos)
  225. def get_versions(repo_names=None):
  226. """get_versions"""
  227. if repo_names is None:
  228. repo_names = get_all_repo_names()
  229. name2versions = OrderedDict()
  230. for repo_name in repo_names:
  231. repo = _GlobalContext.build_repo_instance(repo_name)
  232. versions = repo.get_version()
  233. name2versions[repo_name] = versions
  234. return name2versions