|
| 1 | +import asyncio |
| 2 | +import logging |
| 3 | +import re |
| 4 | +import shutil |
| 5 | +import sys |
| 6 | +import urllib.parse |
| 7 | +from pathlib import Path |
| 8 | +from typing import List, Literal, Optional, Tuple |
| 9 | + |
| 10 | +from plumbum import local |
| 11 | +from sqlalchemy import select |
| 12 | + |
| 13 | +from alws.config import settings |
| 14 | +from alws.dependencies import get_async_db_session |
| 15 | +from alws.models import Repository |
| 16 | +from alws.utils.exporter import download_file, get_repodata_file_links |
| 17 | +from alws.utils.pulp_client import get_pulp_client |
| 18 | + |
| 19 | + |
| 20 | +class BasePulpExporter: |
| 21 | + def __init__( |
| 22 | + self, |
| 23 | + repodata_cache_dir: str, |
| 24 | + logger_name: str = '', |
| 25 | + log_file_path: Path = Path('/tmp/exporter.log'), |
| 26 | + verbose: bool = False, |
| 27 | + export_method: Literal['write', 'hardlink', 'symlink'] = 'hardlink', |
| 28 | + export_path: str = settings.pulp_export_path, |
| 29 | + ): |
| 30 | + self.pulp_client = get_pulp_client() |
| 31 | + self.export_method = export_method |
| 32 | + self.export_path = export_path |
| 33 | + self.createrepo_c = local["createrepo_c"] |
| 34 | + |
| 35 | + self.repodata_cache_dir = Path(repodata_cache_dir).expanduser().absolute() |
| 36 | + self.checksums_cache_dir = self.repodata_cache_dir.joinpath('checksums') |
| 37 | + for dir_path in (self.repodata_cache_dir, self.checksums_cache_dir): |
| 38 | + if dir_path.exists(): |
| 39 | + continue |
| 40 | + dir_path.mkdir() |
| 41 | + |
| 42 | + self.logger = logging.getLogger(logger_name) |
| 43 | + Path(log_file_path).parent.mkdir(exist_ok=True) |
| 44 | + logging.basicConfig( |
| 45 | + format="%(asctime)s %(levelname)-8s %(message)s", |
| 46 | + level=logging.DEBUG if verbose else logging.INFO, |
| 47 | + datefmt="%Y-%m-%d %H:%M:%S", |
| 48 | + handlers=[ |
| 49 | + logging.FileHandler(filename=log_file_path, mode="a"), |
| 50 | + logging.StreamHandler(stream=sys.stdout), |
| 51 | + ], |
| 52 | + ) |
| 53 | + |
| 54 | + def regenerate_repo_metadata(self, repo_path: str): |
| 55 | + partial_path = re.sub(str(settings.pulp_export_path), "", str(repo_path)).strip("/") |
| 56 | + repodata_path = Path(repo_path, "repodata") |
| 57 | + repo_repodata_cache = self.repodata_cache_dir.joinpath(partial_path) |
| 58 | + cache_repodata_dir = repo_repodata_cache.joinpath("repodata") |
| 59 | + self.logger.info('Repodata cache dir: %s', cache_repodata_dir) |
| 60 | + args = [ |
| 61 | + "--update", |
| 62 | + "--keep-all-metadata", |
| 63 | + "--cachedir", |
| 64 | + self.checksums_cache_dir, |
| 65 | + ] |
| 66 | + if repo_repodata_cache.exists(): |
| 67 | + args.extend(["--update-md-path", cache_repodata_dir]) |
| 68 | + args.append(repo_path) |
| 69 | + self.logger.info('Starting createrepo_c') |
| 70 | + _, stdout, _ = self.createrepo_c.run(args=args) |
| 71 | + self.logger.info(stdout) |
| 72 | + self.logger.info('createrepo_c is finished') |
| 73 | + # Cache newly generated repodata into folder for future re-use |
| 74 | + if not repo_repodata_cache.exists(): |
| 75 | + repo_repodata_cache.mkdir(parents=True) |
| 76 | + else: |
| 77 | + # Remove previous repodata before copying new ones |
| 78 | + if cache_repodata_dir.exists(): |
| 79 | + shutil.rmtree(cache_repodata_dir) |
| 80 | + |
| 81 | + shutil.copytree(repodata_path, cache_repodata_dir) |
| 82 | + |
| 83 | + async def create_filesystem_exporters( |
| 84 | + self, |
| 85 | + repository_ids: List[int], |
| 86 | + get_publications: bool = False, |
| 87 | + ): |
| 88 | + async def get_exporter_data(repository: Repository) -> Tuple[str, dict]: |
| 89 | + export_path = str(Path(self.export_path, repository.export_path, "Packages")) |
| 90 | + exporter_name = ( |
| 91 | + f"{repository.name}-{repository.arch}-debug" |
| 92 | + if repository.debug |
| 93 | + else f"{repository.name}-{repository.arch}" |
| 94 | + ) |
| 95 | + fs_exporter_href = await self.pulp_client.create_filesystem_exporter( |
| 96 | + exporter_name, |
| 97 | + export_path, |
| 98 | + export_method=self.export_method, |
| 99 | + ) |
| 100 | + |
| 101 | + repo_latest_version = await self.pulp_client.get_repo_latest_version( |
| 102 | + repository.pulp_href |
| 103 | + ) |
| 104 | + if not repo_latest_version: |
| 105 | + raise ValueError('cannot find latest repo version') |
| 106 | + repo_exporter_dict = { |
| 107 | + "repo_id": repository.id, |
| 108 | + "repo_url": repository.url, |
| 109 | + "repo_latest_version": repo_latest_version, |
| 110 | + "exporter_name": exporter_name, |
| 111 | + "export_path": export_path, |
| 112 | + "exporter_href": fs_exporter_href, |
| 113 | + } |
| 114 | + if get_publications: |
| 115 | + publications = await self.pulp_client.get_rpm_publications( |
| 116 | + repository_version_href=repo_latest_version, |
| 117 | + include_fields=["pulp_href"], |
| 118 | + ) |
| 119 | + if publications: |
| 120 | + publication_href = publications[0].get("pulp_href") |
| 121 | + repo_exporter_dict["publication_href"] = publication_href |
| 122 | + return fs_exporter_href, repo_exporter_dict |
| 123 | + |
| 124 | + async with get_async_db_session() as session: |
| 125 | + query = select(Repository).where(Repository.id.in_(repository_ids)) |
| 126 | + result = await session.execute(query) |
| 127 | + repositories = list(result.scalars().all()) |
| 128 | + |
| 129 | + results = await asyncio.gather(*(get_exporter_data(repo) for repo in repositories)) |
| 130 | + |
| 131 | + return list(dict(results).values()) |
| 132 | + |
| 133 | + async def download_repodata(self, repodata_path, repodata_url): |
| 134 | + file_links = await get_repodata_file_links(repodata_url) |
| 135 | + for link in file_links: |
| 136 | + file_name = Path(link).name |
| 137 | + if file_name.endswith('..'): |
| 138 | + continue |
| 139 | + self.logger.info("Downloading repodata from %s", link) |
| 140 | + await download_file(link, Path(repodata_path, file_name)) |
| 141 | + |
| 142 | + async def _export_repository(self, exporter: dict) -> Optional[str]: |
| 143 | + self.logger.info( |
| 144 | + "Exporting repository using following data: %s", |
| 145 | + str(exporter), |
| 146 | + ) |
| 147 | + export_path = exporter["export_path"] |
| 148 | + href = exporter["exporter_href"] |
| 149 | + repository_version = exporter["repo_latest_version"] |
| 150 | + try: |
| 151 | + await self.pulp_client.export_to_filesystem(href, repository_version) |
| 152 | + except Exception: |
| 153 | + self.logger.exception( |
| 154 | + "Cannot export repository via %s", |
| 155 | + str(exporter), |
| 156 | + ) |
| 157 | + return |
| 158 | + parent_dir = Path(export_path).parent |
| 159 | + if not parent_dir.exists(): |
| 160 | + self.logger.info( |
| 161 | + "Repository %s directory is absent", |
| 162 | + exporter["exporter_name"], |
| 163 | + ) |
| 164 | + return |
| 165 | + |
| 166 | + repodata_path = parent_dir.joinpath("repodata").absolute() |
| 167 | + repodata_url = urllib.parse.urljoin(exporter["repo_url"], "repodata/") |
| 168 | + if repodata_path.exists(): |
| 169 | + shutil.rmtree(repodata_path) |
| 170 | + repodata_path.mkdir() |
| 171 | + self.logger.info('Downloading repodata from %s', repodata_url) |
| 172 | + try: |
| 173 | + await self.download_repodata(repodata_path, repodata_url) |
| 174 | + except Exception as e: |
| 175 | + self.logger.exception("Cannot download repodata file: %s", str(e)) |
| 176 | + |
| 177 | + return export_path |
| 178 | + |
| 179 | + async def export_repositories(self, repo_ids: List[int]) -> List[str]: |
| 180 | + exporters = await self.create_filesystem_exporters(repo_ids) |
| 181 | + results = await asyncio.gather(*(self._export_repository(e) for e in exporters)) |
| 182 | + return [path for path in results if path] |
0 commit comments