repo.py 14 KB

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