repo.py 14 KB

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