1# 2# SPDX-License-Identifier: GPL-2.0-only 3# 4 5import shutil 6import subprocess 7from oe.package_manager import * 8 9class RpmIndexer(Indexer): 10 def write_index(self): 11 self.do_write_index(self.deploy_dir) 12 13 def do_write_index(self, deploy_dir): 14 if self.d.getVar('PACKAGE_FEED_SIGN') == '1': 15 signer = get_signer(self.d, self.d.getVar('PACKAGE_FEED_GPG_BACKEND')) 16 else: 17 signer = None 18 19 createrepo_c = bb.utils.which(os.environ['PATH'], "createrepo_c") 20 result = create_index("%s --update -q %s" % (createrepo_c, deploy_dir)) 21 if result: 22 bb.fatal(result) 23 24 # Sign repomd 25 if signer: 26 sig_type = self.d.getVar('PACKAGE_FEED_GPG_SIGNATURE_TYPE') 27 is_ascii_sig = (sig_type.upper() != "BIN") 28 signer.detach_sign(os.path.join(deploy_dir, 'repodata', 'repomd.xml'), 29 self.d.getVar('PACKAGE_FEED_GPG_NAME'), 30 self.d.getVar('PACKAGE_FEED_GPG_PASSPHRASE_FILE'), 31 armor=is_ascii_sig) 32 33class RpmSubdirIndexer(RpmIndexer): 34 def write_index(self): 35 bb.note("Generating package index for %s" %(self.deploy_dir)) 36 # Remove the existing repodata to ensure that we re-generate it no matter what 37 bb.utils.remove(os.path.join(self.deploy_dir, "repodata"), recurse=True) 38 39 self.do_write_index(self.deploy_dir) 40 for entry in os.walk(self.deploy_dir): 41 if os.path.samefile(self.deploy_dir, entry[0]): 42 for dir in entry[1]: 43 if dir != 'repodata': 44 dir_path = oe.path.join(self.deploy_dir, dir) 45 bb.note("Generating package index for %s" %(dir_path)) 46 self.do_write_index(dir_path) 47 48 49class PMPkgsList(PkgsList): 50 def list_pkgs(self): 51 return RpmPM(self.d, self.rootfs_dir, self.d.getVar('TARGET_VENDOR'), needfeed=False).list_installed() 52 53class RpmPM(PackageManager): 54 def __init__(self, 55 d, 56 target_rootfs, 57 target_vendor, 58 task_name='target', 59 arch_var=None, 60 os_var=None, 61 rpm_repo_workdir="oe-rootfs-repo", 62 filterbydependencies=True, 63 needfeed=True): 64 super(RpmPM, self).__init__(d, target_rootfs) 65 self.target_vendor = target_vendor 66 self.task_name = task_name 67 if arch_var == None: 68 self.archs = self.d.getVar('ALL_MULTILIB_PACKAGE_ARCHS').replace("-","_") 69 else: 70 self.archs = self.d.getVar(arch_var).replace("-","_") 71 if task_name == "host": 72 self.primary_arch = self.d.getVar('SDK_ARCH') 73 else: 74 self.primary_arch = self.d.getVar('MACHINE_ARCH') 75 76 if needfeed: 77 self.rpm_repo_dir = oe.path.join(self.d.getVar('WORKDIR'), rpm_repo_workdir) 78 create_packages_dir(self.d, oe.path.join(self.rpm_repo_dir, "rpm"), d.getVar("DEPLOY_DIR_RPM"), "package_write_rpm", filterbydependencies) 79 80 self.saved_packaging_data = self.d.expand('${T}/saved_packaging_data/%s' % self.task_name) 81 if not os.path.exists(self.d.expand('${T}/saved_packaging_data')): 82 bb.utils.mkdirhier(self.d.expand('${T}/saved_packaging_data')) 83 self.packaging_data_dirs = ['etc/rpm', 'etc/rpmrc', 'etc/dnf', 'var/lib/rpm', 'var/lib/dnf', 'var/cache/dnf'] 84 self.solution_manifest = self.d.expand('${T}/saved/%s_solution' % 85 self.task_name) 86 if not os.path.exists(self.d.expand('${T}/saved')): 87 bb.utils.mkdirhier(self.d.expand('${T}/saved')) 88 89 def _configure_dnf(self): 90 # libsolv handles 'noarch' internally, we don't need to specify it explicitly 91 archs = [i for i in reversed(self.archs.split()) if i not in ["any", "all", "noarch"]] 92 # This prevents accidental matching against libsolv's built-in policies 93 if len(archs) <= 1: 94 archs = archs + ["bogusarch"] 95 # This architecture needs to be upfront so that packages using it are properly prioritized 96 archs = ["sdk_provides_dummy_target"] + archs 97 confdir = "%s/%s" %(self.target_rootfs, "etc/dnf/vars/") 98 bb.utils.mkdirhier(confdir) 99 open(confdir + "arch", 'w').write(":".join(archs)) 100 distro_codename = self.d.getVar('DISTRO_CODENAME') 101 open(confdir + "releasever", 'w').write(distro_codename if distro_codename is not None else '') 102 103 open(oe.path.join(self.target_rootfs, "etc/dnf/dnf.conf"), 'w').write("") 104 105 106 def _configure_rpm(self): 107 # We need to configure rpm to use our primary package architecture as the installation architecture, 108 # and to make it compatible with other package architectures that we use. 109 # Otherwise it will refuse to proceed with packages installation. 110 platformconfdir = "%s/%s" %(self.target_rootfs, "etc/rpm/") 111 rpmrcconfdir = "%s/%s" %(self.target_rootfs, "etc/") 112 bb.utils.mkdirhier(platformconfdir) 113 open(platformconfdir + "platform", 'w').write("%s-pc-linux" % self.primary_arch) 114 with open(rpmrcconfdir + "rpmrc", 'w') as f: 115 f.write("arch_compat: %s: %s\n" % (self.primary_arch, self.archs if len(self.archs) > 0 else self.primary_arch)) 116 f.write("buildarch_compat: %s: noarch\n" % self.primary_arch) 117 118 open(platformconfdir + "macros", 'w').write("%_transaction_color 7\n") 119 if self.d.getVar('RPM_PREFER_ELF_ARCH'): 120 open(platformconfdir + "macros", 'a').write("%%_prefer_color %s" % (self.d.getVar('RPM_PREFER_ELF_ARCH'))) 121 122 if self.d.getVar('RPM_SIGN_PACKAGES') == '1': 123 signer = get_signer(self.d, self.d.getVar('RPM_GPG_BACKEND')) 124 pubkey_path = oe.path.join(self.d.getVar('B'), 'rpm-key') 125 signer.export_pubkey(pubkey_path, self.d.getVar('RPM_GPG_NAME')) 126 rpm_bin = bb.utils.which(os.getenv('PATH'), "rpmkeys") 127 cmd = [rpm_bin, '--root=%s' % self.target_rootfs, '--import', pubkey_path] 128 try: 129 subprocess.check_output(cmd, stderr=subprocess.STDOUT) 130 except subprocess.CalledProcessError as e: 131 bb.fatal("Importing GPG key failed. Command '%s' " 132 "returned %d:\n%s" % (' '.join(cmd), e.returncode, e.output.decode("utf-8"))) 133 134 def create_configs(self): 135 self._configure_dnf() 136 self._configure_rpm() 137 138 def write_index(self): 139 lockfilename = self.d.getVar('DEPLOY_DIR_RPM') + "/rpm.lock" 140 lf = bb.utils.lockfile(lockfilename, False) 141 RpmIndexer(self.d, self.rpm_repo_dir).write_index() 142 bb.utils.unlockfile(lf) 143 144 def insert_feeds_uris(self, feed_uris, feed_base_paths, feed_archs): 145 from urllib.parse import urlparse 146 147 if feed_uris == "": 148 return 149 150 gpg_opts = '' 151 if self.d.getVar('PACKAGE_FEED_SIGN') == '1': 152 gpg_opts += 'repo_gpgcheck=1\n' 153 gpg_opts += 'gpgkey=file://%s/pki/packagefeed-gpg/PACKAGEFEED-GPG-KEY-%s-%s\n' % (self.d.getVar('sysconfdir'), self.d.getVar('DISTRO'), self.d.getVar('DISTRO_CODENAME')) 154 155 if self.d.getVar('RPM_SIGN_PACKAGES') != '1': 156 gpg_opts += 'gpgcheck=0\n' 157 158 bb.utils.mkdirhier(oe.path.join(self.target_rootfs, "etc", "yum.repos.d")) 159 remote_uris = self.construct_uris(feed_uris.split(), feed_base_paths.split()) 160 for uri in remote_uris: 161 repo_base = "oe-remote-repo" + "-".join(urlparse(uri).path.split("/")) 162 if feed_archs is not None: 163 for arch in feed_archs.split(): 164 repo_uri = uri + "/" + arch 165 repo_id = "oe-remote-repo" + "-".join(urlparse(repo_uri).path.split("/")) 166 repo_name = "OE Remote Repo:" + " ".join(urlparse(repo_uri).path.split("/")) 167 open(oe.path.join(self.target_rootfs, "etc", "yum.repos.d", repo_base + ".repo"), 'a').write( 168 "[%s]\nname=%s\nbaseurl=%s\n%s\n" % (repo_id, repo_name, repo_uri, gpg_opts)) 169 else: 170 repo_name = "OE Remote Repo:" + " ".join(urlparse(uri).path.split("/")) 171 repo_uri = uri 172 open(oe.path.join(self.target_rootfs, "etc", "yum.repos.d", repo_base + ".repo"), 'w').write( 173 "[%s]\nname=%s\nbaseurl=%s\n%s" % (repo_base, repo_name, repo_uri, gpg_opts)) 174 175 def _prepare_pkg_transaction(self): 176 os.environ['D'] = self.target_rootfs 177 os.environ['OFFLINE_ROOT'] = self.target_rootfs 178 os.environ['IPKG_OFFLINE_ROOT'] = self.target_rootfs 179 os.environ['OPKG_OFFLINE_ROOT'] = self.target_rootfs 180 os.environ['INTERCEPT_DIR'] = self.intercepts_dir 181 os.environ['NATIVE_ROOT'] = self.d.getVar('STAGING_DIR_NATIVE') 182 183 184 def install(self, pkgs, attempt_only = False): 185 if len(pkgs) == 0: 186 return 187 self._prepare_pkg_transaction() 188 189 bad_recommendations = self.d.getVar('BAD_RECOMMENDATIONS') 190 package_exclude = self.d.getVar('PACKAGE_EXCLUDE') 191 exclude_pkgs = (bad_recommendations.split() if bad_recommendations else []) + (package_exclude.split() if package_exclude else []) 192 193 output = self._invoke_dnf((["--skip-broken"] if attempt_only else []) + 194 (["-x", ",".join(exclude_pkgs)] if len(exclude_pkgs) > 0 else []) + 195 (["--setopt=install_weak_deps=False"] if self.d.getVar('NO_RECOMMENDATIONS') == "1" else []) + 196 (["--nogpgcheck"] if self.d.getVar('RPM_SIGN_PACKAGES') != '1' else ["--setopt=gpgcheck=True"]) + 197 ["install"] + 198 pkgs) 199 200 failed_scriptlets_pkgnames = collections.OrderedDict() 201 for line in output.splitlines(): 202 if line.startswith("Error: Systemctl"): 203 bb.error(line) 204 205 if line.startswith("Error in POSTIN scriptlet in rpm package"): 206 failed_scriptlets_pkgnames[line.split()[-1]] = True 207 208 if len(failed_scriptlets_pkgnames) > 0: 209 failed_postinsts_abort(list(failed_scriptlets_pkgnames.keys()), self.d.expand("${T}/log.do_${BB_CURRENTTASK}")) 210 211 def remove(self, pkgs, with_dependencies = True): 212 if not pkgs: 213 return 214 215 self._prepare_pkg_transaction() 216 217 if with_dependencies: 218 self._invoke_dnf(["remove"] + pkgs) 219 else: 220 cmd = bb.utils.which(os.getenv('PATH'), "rpm") 221 args = ["-e", "-v", "--nodeps", "--root=%s" %self.target_rootfs] 222 223 try: 224 bb.note("Running %s" % ' '.join([cmd] + args + pkgs)) 225 output = subprocess.check_output([cmd] + args + pkgs, stderr=subprocess.STDOUT).decode("utf-8") 226 bb.note(output) 227 except subprocess.CalledProcessError as e: 228 bb.fatal("Could not invoke rpm. Command " 229 "'%s' returned %d:\n%s" % (' '.join([cmd] + args + pkgs), e.returncode, e.output.decode("utf-8"))) 230 231 def upgrade(self): 232 self._prepare_pkg_transaction() 233 self._invoke_dnf(["upgrade"]) 234 235 def autoremove(self): 236 self._prepare_pkg_transaction() 237 self._invoke_dnf(["autoremove"]) 238 239 def remove_packaging_data(self): 240 self._invoke_dnf(["clean", "all"]) 241 for dir in self.packaging_data_dirs: 242 bb.utils.remove(oe.path.join(self.target_rootfs, dir), True) 243 244 def backup_packaging_data(self): 245 # Save the packaging dirs for increment rpm image generation 246 if os.path.exists(self.saved_packaging_data): 247 bb.utils.remove(self.saved_packaging_data, True) 248 for i in self.packaging_data_dirs: 249 source_dir = oe.path.join(self.target_rootfs, i) 250 target_dir = oe.path.join(self.saved_packaging_data, i) 251 if os.path.isdir(source_dir): 252 shutil.copytree(source_dir, target_dir, symlinks=True) 253 elif os.path.isfile(source_dir): 254 shutil.copy2(source_dir, target_dir) 255 256 def recovery_packaging_data(self): 257 # Move the rpmlib back 258 if os.path.exists(self.saved_packaging_data): 259 for i in self.packaging_data_dirs: 260 target_dir = oe.path.join(self.target_rootfs, i) 261 if os.path.exists(target_dir): 262 bb.utils.remove(target_dir, True) 263 source_dir = oe.path.join(self.saved_packaging_data, i) 264 if os.path.isdir(source_dir): 265 shutil.copytree(source_dir, target_dir, symlinks=True) 266 elif os.path.isfile(source_dir): 267 shutil.copy2(source_dir, target_dir) 268 269 def list_installed(self): 270 output = self._invoke_dnf(["repoquery", "--installed", "--queryformat", "Package: %{name} %{arch} %{version} %{name}-%{version}-%{release}.%{arch}.rpm\nDependencies:\n%{requires}\nRecommendations:\n%{recommends}\nDependenciesEndHere:\n"], 271 print_output = False) 272 packages = {} 273 current_package = None 274 current_deps = None 275 current_state = "initial" 276 for line in output.splitlines(): 277 if line.startswith("Package:"): 278 package_info = line.split(" ")[1:] 279 current_package = package_info[0] 280 package_arch = package_info[1] 281 package_version = package_info[2] 282 package_rpm = package_info[3] 283 packages[current_package] = {"arch":package_arch, "ver":package_version, "filename":package_rpm} 284 current_deps = [] 285 elif line.startswith("Dependencies:"): 286 current_state = "dependencies" 287 elif line.startswith("Recommendations"): 288 current_state = "recommendations" 289 elif line.startswith("DependenciesEndHere:"): 290 current_state = "initial" 291 packages[current_package]["deps"] = current_deps 292 elif len(line) > 0: 293 if current_state == "dependencies": 294 current_deps.append(line) 295 elif current_state == "recommendations": 296 current_deps.append("%s [REC]" % line) 297 298 return packages 299 300 def update(self): 301 self._invoke_dnf(["makecache", "--refresh"]) 302 303 def _invoke_dnf(self, dnf_args, fatal = True, print_output = True ): 304 os.environ['RPM_ETCCONFIGDIR'] = self.target_rootfs 305 306 dnf_cmd = bb.utils.which(os.getenv('PATH'), "dnf") 307 standard_dnf_args = ["-v", "--rpmverbosity=info", "-y", 308 "-c", oe.path.join(self.target_rootfs, "etc/dnf/dnf.conf"), 309 "--setopt=reposdir=%s" %(oe.path.join(self.target_rootfs, "etc/yum.repos.d")), 310 "--installroot=%s" % (self.target_rootfs), 311 "--setopt=logdir=%s" % (self.d.getVar('T')) 312 ] 313 if hasattr(self, "rpm_repo_dir"): 314 standard_dnf_args.append("--repofrompath=oe-repo,%s" % (self.rpm_repo_dir)) 315 cmd = [dnf_cmd] + standard_dnf_args + dnf_args 316 bb.note('Running %s' % ' '.join(cmd)) 317 try: 318 output = subprocess.check_output(cmd,stderr=subprocess.STDOUT).decode("utf-8") 319 if print_output: 320 bb.debug(1, output) 321 return output 322 except subprocess.CalledProcessError as e: 323 if print_output: 324 (bb.note, bb.fatal)[fatal]("Could not invoke dnf. Command " 325 "'%s' returned %d:\n%s" % (' '.join(cmd), e.returncode, e.output.decode("utf-8"))) 326 else: 327 (bb.note, bb.fatal)[fatal]("Could not invoke dnf. Command " 328 "'%s' returned %d:" % (' '.join(cmd), e.returncode)) 329 return e.output.decode("utf-8") 330 331 def dump_install_solution(self, pkgs): 332 open(self.solution_manifest, 'w').write(" ".join(pkgs)) 333 return pkgs 334 335 def load_old_install_solution(self): 336 if not os.path.exists(self.solution_manifest): 337 return [] 338 with open(self.solution_manifest, 'r') as fd: 339 return fd.read().split() 340 341 def _script_num_prefix(self, path): 342 files = os.listdir(path) 343 numbers = set() 344 numbers.add(99) 345 for f in files: 346 numbers.add(int(f.split("-")[0])) 347 return max(numbers) + 1 348 349 def save_rpmpostinst(self, pkg): 350 bb.note("Saving postinstall script of %s" % (pkg)) 351 cmd = bb.utils.which(os.getenv('PATH'), "rpm") 352 args = ["-q", "--root=%s" % self.target_rootfs, "--queryformat", "%{postin}", pkg] 353 354 try: 355 output = subprocess.check_output([cmd] + args,stderr=subprocess.STDOUT).decode("utf-8") 356 except subprocess.CalledProcessError as e: 357 bb.fatal("Could not invoke rpm. Command " 358 "'%s' returned %d:\n%s" % (' '.join([cmd] + args), e.returncode, e.output.decode("utf-8"))) 359 360 # may need to prepend #!/bin/sh to output 361 362 target_path = oe.path.join(self.target_rootfs, self.d.expand('${sysconfdir}/rpm-postinsts/')) 363 bb.utils.mkdirhier(target_path) 364 num = self._script_num_prefix(target_path) 365 saved_script_name = oe.path.join(target_path, "%d-%s" % (num, pkg)) 366 open(saved_script_name, 'w').write(output) 367 os.chmod(saved_script_name, 0o755) 368 369 def _handle_intercept_failure(self, registered_pkgs): 370 rpm_postinsts_dir = self.target_rootfs + self.d.expand('${sysconfdir}/rpm-postinsts/') 371 bb.utils.mkdirhier(rpm_postinsts_dir) 372 373 # Save the package postinstalls in /etc/rpm-postinsts 374 for pkg in registered_pkgs.split(): 375 self.save_rpmpostinst(pkg) 376 377 def extract(self, pkg): 378 output = self._invoke_dnf(["repoquery", "--queryformat", "%{location}", pkg]) 379 pkg_name = output.splitlines()[-1] 380 if not pkg_name.endswith(".rpm"): 381 bb.fatal("dnf could not find package %s in repository: %s" %(pkg, output)) 382 pkg_path = oe.path.join(self.rpm_repo_dir, pkg_name) 383 384 cpio_cmd = bb.utils.which(os.getenv("PATH"), "cpio") 385 rpm2cpio_cmd = bb.utils.which(os.getenv("PATH"), "rpm2cpio") 386 387 if not os.path.isfile(pkg_path): 388 bb.fatal("Unable to extract package for '%s'." 389 "File %s doesn't exists" % (pkg, pkg_path)) 390 391 tmp_dir = tempfile.mkdtemp() 392 current_dir = os.getcwd() 393 os.chdir(tmp_dir) 394 395 try: 396 cmd = "%s %s | %s -idmv" % (rpm2cpio_cmd, pkg_path, cpio_cmd) 397 output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True) 398 except subprocess.CalledProcessError as e: 399 bb.utils.remove(tmp_dir, recurse=True) 400 bb.fatal("Unable to extract %s package. Command '%s' " 401 "returned %d:\n%s" % (pkg_path, cmd, e.returncode, e.output.decode("utf-8"))) 402 except OSError as e: 403 bb.utils.remove(tmp_dir, recurse=True) 404 bb.fatal("Unable to extract %s package. Command '%s' " 405 "returned %d:\n%s at %s" % (pkg_path, cmd, e.errno, e.strerror, e.filename)) 406 407 bb.note("Extracted %s to %s" % (pkg_path, tmp_dir)) 408 os.chdir(current_dir) 409 410 return tmp_dir 411