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