repo.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  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 importlib
  15. import os
  16. import os.path as osp
  17. import shutil
  18. import tempfile
  19. from packaging.requirements import Requirement
  20. from ..utils import logging
  21. from ..utils.download import download_and_extract
  22. from ..utils.file_interface import custom_open
  23. from ..utils.install import (
  24. install_packages,
  25. install_packages_from_requirements_file,
  26. uninstall_packages,
  27. )
  28. from .meta import REPO_DOWNLOAD_BASE, get_repo_meta
  29. from .utils import (
  30. check_package_installation,
  31. fetch_repo_using_git,
  32. install_external_deps,
  33. mute,
  34. remove_repo_using_rm,
  35. reset_repo_using_git,
  36. switch_working_dir,
  37. )
  38. __all__ = ["build_repo_instance", "build_repo_group_installer"]
  39. def build_repo_instance(repo_name, *args, **kwargs):
  40. """build_repo_instance"""
  41. # XXX: Hard-code type
  42. repo_cls = PPRepository
  43. repo_instance = repo_cls(repo_name, *args, **kwargs)
  44. return repo_instance
  45. def build_repo_group_installer(*repos):
  46. """build_repo_group_installer"""
  47. return RepositoryGroupInstaller(list(repos))
  48. def build_repo_group_getter(*repos):
  49. """build_repo_group_getter"""
  50. return RepositoryGroupGetter(list(repos))
  51. class PPRepository(object):
  52. """
  53. Installation, initialization, and PDX module import handler for a
  54. PaddlePaddle repository.
  55. """
  56. def __init__(self, name, repo_parent_dir, pdx_collection_mod):
  57. super().__init__()
  58. self.name = name
  59. self.repo_parent_dir = repo_parent_dir
  60. self.root_dir = osp.join(repo_parent_dir, self.name)
  61. self.meta = get_repo_meta(self.name)
  62. self.git_path = self.meta["git_path"]
  63. self.lib_name = self.meta["lib_name"]
  64. self.pkg_name = self.meta.get("pkg_name", None)
  65. self.pdx_mod_name = (
  66. pdx_collection_mod.__name__ + "." + self.meta["pdx_pkg_name"]
  67. )
  68. self.main_reqs_file = self.meta.get("main_reqs_file", "requirements.txt")
  69. def initialize(self):
  70. """initialize"""
  71. if not self.check_installation():
  72. return False
  73. if "path_env" in self.meta:
  74. # Set env var
  75. os.environ[self.meta["path_env"]] = osp.abspath(self.root_dir)
  76. # NOTE: By calling `self.get_pdx()` we actually loads the repo PDX package
  77. # and do all registration.
  78. self.get_pdx()
  79. return True
  80. def check_installation(self):
  81. """check_installation"""
  82. return osp.exists(osp.join(self.root_dir, ".installed"))
  83. def replace_repo_deps(self, deps_to_replace, src_requirements):
  84. """replace_repo_deps"""
  85. with custom_open(src_requirements, "r") as file:
  86. lines = file.readlines()
  87. existing_deps = []
  88. for line in lines:
  89. line = line.strip()
  90. if not line or line.startswith("#"):
  91. continue
  92. dep_to_replace = next((dep for dep in deps_to_replace if dep in line), None)
  93. if dep_to_replace:
  94. if deps_to_replace[dep_to_replace] == "None":
  95. continue
  96. else:
  97. existing_deps.append(
  98. f"{dep_to_replace}=={deps_to_replace[dep_to_replace]}"
  99. )
  100. else:
  101. existing_deps.append(line)
  102. with open(src_requirements, "w") as file:
  103. file.writelines([l + "\n" for l in existing_deps])
  104. def check_repo_exiting(self):
  105. """check_repo_exiting"""
  106. return osp.exists(osp.join(self.root_dir, ".git"))
  107. def install_packages(self, clean=True):
  108. """install_packages"""
  109. if self.meta["install_pkg"]:
  110. editable = self.meta.get("editable", True)
  111. if editable:
  112. logging.warning(f"{self.pkg_name} will be installed in editable mode.")
  113. with switch_working_dir(self.root_dir):
  114. try:
  115. pip_install_opts = ["--no-deps"]
  116. if editable:
  117. pip_install_opts.append("-e")
  118. install_packages(["."], pip_install_opts=pip_install_opts)
  119. install_external_deps(self.name, self.root_dir)
  120. finally:
  121. if clean:
  122. # Clean build artifacts
  123. tmp_build_dir = "build"
  124. if osp.exists(tmp_build_dir):
  125. shutil.rmtree(tmp_build_dir)
  126. for e in self.meta.get("extra", []):
  127. if isinstance(e, tuple):
  128. with switch_working_dir(osp.join(self.root_dir, e[0])):
  129. try:
  130. pip_install_opts = ["--no-deps"]
  131. if e[3]:
  132. pip_install_opts.append("-e")
  133. install_packages(["."], pip_install_opts=pip_install_opts)
  134. finally:
  135. if clean:
  136. tmp_build_dir = "build"
  137. if osp.exists(tmp_build_dir):
  138. shutil.rmtree(tmp_build_dir)
  139. def uninstall_packages(self):
  140. """uninstall_packages"""
  141. pkgs = []
  142. if self.install_pkg:
  143. pkgs.append(self.pkg_name)
  144. for e in self.meta.get("extra", []):
  145. if isinstance(e, tuple):
  146. pkgs.append(e[1])
  147. uninstall_packages(pkgs)
  148. def mark_installed(self):
  149. with open(osp.join(self.root_dir, ".installed"), "wb"):
  150. pass
  151. def mark_uninstalled(self):
  152. os.unlink(osp.join(self.root_dir, ".installed"))
  153. def download(self):
  154. """download from remote"""
  155. download_url = f"{REPO_DOWNLOAD_BASE}{self.name}.tar"
  156. os.makedirs(self.repo_parent_dir, exist_ok=True)
  157. download_and_extract(download_url, self.repo_parent_dir, self.name)
  158. # reset_repo_using_git('FETCH_HEAD')
  159. def remove(self):
  160. """remove"""
  161. with switch_working_dir(self.repo_parent_dir):
  162. remove_repo_using_rm(self.name)
  163. def update(self, platform=None):
  164. """update"""
  165. branch = self.meta.get("branch", None)
  166. git_url = f"https://{platform}{self.git_path}"
  167. with switch_working_dir(self.root_dir):
  168. try:
  169. fetch_repo_using_git(branch=branch, url=git_url)
  170. reset_repo_using_git("FETCH_HEAD")
  171. except Exception as e:
  172. logging.warning(
  173. f"Update {self.name} from {git_url} failed, check your network connection. Error:\n{e}"
  174. )
  175. def _get_lib(self):
  176. """_get_lib"""
  177. import importlib.util
  178. importlib.invalidate_caches()
  179. try:
  180. with mute():
  181. return importlib.import_module(self.lib_name)
  182. except ImportError:
  183. return None
  184. def get_pdx(self):
  185. """get_pdx"""
  186. return importlib.import_module(self.pdx_mod_name)
  187. def get_deps(self, deps_to_replace=None):
  188. """get_deps"""
  189. # Merge requirement files
  190. req_list = [self.main_reqs_file]
  191. for e in self.meta.get("extra", []):
  192. if isinstance(e, tuple):
  193. e = e[2] or osp.join(e[0], "requirements.txt")
  194. req_list.append(e)
  195. if deps_to_replace is not None:
  196. deps_dict = {}
  197. for dep in deps_to_replace:
  198. part, version = dep.split("=")
  199. repo_name, dep_name = part.split(".")
  200. deps_dict[repo_name] = {dep_name: version}
  201. src_requirements = osp.join(self.root_dir, "requirements.txt")
  202. if self.name in deps_dict:
  203. self.replace_repo_deps(deps_dict[self.name], src_requirements)
  204. deps = []
  205. for req in req_list:
  206. with open(osp.join(self.root_dir, req), "r", encoding="utf-8") as f:
  207. deps.append(f.read())
  208. for dep in self.meta.get("pdx_pkg_deps", []):
  209. deps.append(dep)
  210. deps = "\n".join(deps)
  211. return deps
  212. def get_version(self):
  213. """get_version"""
  214. version_file = osp.join(self.root_dir, ".pdx_gen.version")
  215. with open(version_file, "r", encoding="utf-8") as f:
  216. lines = f.readlines()
  217. sta_ver = lines[0].rstrip()
  218. commit = lines[1].rstrip()
  219. ret = [sta_ver, commit]
  220. # TODO: Get dynamic version in a subprocess.
  221. ret.append(None)
  222. return ret
  223. def __str__(self):
  224. return f"({self.name}, {id(self)})"
  225. class RepositoryGroupInstaller(object):
  226. """RepositoryGroupInstaller"""
  227. def __init__(self, repos):
  228. super().__init__()
  229. self.repos = repos
  230. def install(
  231. self,
  232. force_reinstall=False,
  233. no_deps=False,
  234. constraints=None,
  235. deps_to_replace=None,
  236. ):
  237. """install"""
  238. # Rollback on failure is not yet supported. A failed installation
  239. # could leave a broken environment.
  240. if force_reinstall:
  241. self.uninstall()
  242. ins_flags = []
  243. repos = self._sort_repos(self.repos, check_missing=True)
  244. for repo in repos:
  245. if force_reinstall or not repo.check_installation():
  246. ins_flags.append(True)
  247. else:
  248. ins_flags.append(False)
  249. if not no_deps:
  250. # We collect the dependencies and install them all at once
  251. # such that we can make use of the pip resolver.
  252. self.install_deps(constraints=constraints, deps_to_replace=deps_to_replace)
  253. # XXX: For historical reasons the repo packages are sequentially
  254. # installed, and we have no failure rollbacks. Meanwhile, installation
  255. # failure of one repo package aborts the entire installation process.
  256. for ins_flag, repo in zip(ins_flags, repos):
  257. if ins_flag:
  258. repo.install_packages()
  259. repo.mark_installed()
  260. def uninstall(self):
  261. """uninstall"""
  262. repos = self._sort_repos(self.repos, check_missing=False)
  263. repos = repos[::-1]
  264. for repo in repos:
  265. if repo.check_installation():
  266. # NOTE: Dependencies are not uninstalled.
  267. repo.uninstall_packages()
  268. repo.mark_uninstalled()
  269. def get_deps(self, deps_to_replace=None):
  270. """get_deps"""
  271. deps_list = []
  272. repos = self._sort_repos(self.repos, check_missing=True)
  273. for repo in repos:
  274. deps = repo.get_deps(deps_to_replace=deps_to_replace)
  275. deps = self._normalize_deps(deps, headline=f"# {repo.name} dependencies")
  276. deps_list.append(deps)
  277. # Add an extra new line to separate dependencies of different repos.
  278. return "\n\n".join(deps_list)
  279. def install_deps(self, constraints, deps_to_replace=None):
  280. """install_deps"""
  281. deps_str = self.get_deps(deps_to_replace=deps_to_replace)
  282. with tempfile.TemporaryDirectory() as td:
  283. req_file = osp.join(td, "requirements.txt")
  284. with open(req_file, "w", encoding="utf-8") as fr:
  285. fr.write(deps_str)
  286. if constraints is not None:
  287. cons_file = osp.join(td, "constraints.txt")
  288. with open(cons_file, "w", encoding="utf-8") as fc:
  289. fc.write(constraints)
  290. cons_files = [cons_file]
  291. else:
  292. cons_files = []
  293. pip_install_opts = []
  294. for f in cons_files:
  295. pip_install_opts.append("-c")
  296. pip_install_opts.append(f)
  297. install_packages_from_requirements_file(
  298. req_file, pip_install_opts=pip_install_opts
  299. )
  300. def _sort_repos(self, repos, check_missing=False):
  301. # We sort the repos to ensure that the dependencies precede the
  302. # dependant in the list.
  303. name_meta_pairs = []
  304. for repo in repos:
  305. name_meta_pairs.append((repo.name, repo.meta))
  306. unique_pairs = []
  307. hashset = set()
  308. for name, meta in name_meta_pairs:
  309. if name in hashset:
  310. continue
  311. else:
  312. unique_pairs.append((name, meta))
  313. hashset.add(name)
  314. sorted_repos = []
  315. missing_names = []
  316. name2repo = {repo.name: repo for repo in repos}
  317. for name, meta in unique_pairs:
  318. if name in name2repo:
  319. repo = name2repo[name]
  320. sorted_repos.append(repo)
  321. else:
  322. missing_names.append(name)
  323. if check_missing and len(missing_names) > 0:
  324. be = "is" if len(missing_names) == 1 else "are"
  325. raise RuntimeError(f"{missing_names} {be} required in the installation.")
  326. else:
  327. assert len(sorted_repos) == len(self.repos)
  328. return sorted_repos
  329. def _normalize_deps(self, deps, headline=None):
  330. repo_pkgs = set(repo.pkg_name for repo in self.repos)
  331. lines = []
  332. if headline is not None:
  333. lines.append(headline)
  334. for line in deps.splitlines():
  335. line_s = line.strip()
  336. if not line_s:
  337. continue
  338. pos = line_s.find("#")
  339. if pos == 0:
  340. continue
  341. elif pos > 0:
  342. line_s = line_s[:pos]
  343. # If `line` is not an empty line or a comment, it must be a requirement specifier.
  344. # Other forms may cause a parse error.
  345. req = Requirement(line_s)
  346. if req.name in repo_pkgs:
  347. # Skip repo packages
  348. continue
  349. elif check_package_installation(req.name):
  350. continue
  351. else:
  352. lines.append(line_s)
  353. return "\n".join(lines)
  354. class RepositoryGroupGetter(object):
  355. """RepositoryGroupGetter"""
  356. def __init__(self, repos):
  357. super().__init__()
  358. self.repos = repos
  359. def get(self, force=False, platform=None):
  360. """clone"""
  361. if force:
  362. self.remove()
  363. for repo in self.repos:
  364. repo.download()
  365. repo.update(platform=platform)
  366. def remove(self):
  367. """remove"""
  368. for repo in self.repos:
  369. repo.remove()