blob: 6fd2f021b688c239e3b9c3afc4cd1fc537b68317 [file] [log] [blame]
Andrew Geissler635e0e42020-08-21 15:58:33 -05001#
2# SPDX-License-Identifier: GPL-2.0-only
3#
4
5import re
6import shutil
7import subprocess
8from oe.package_manager import *
9
10class OpkgIndexer(Indexer):
11 def write_index(self):
12 arch_vars = ["ALL_MULTILIB_PACKAGE_ARCHS",
13 "SDK_PACKAGE_ARCHS",
14 ]
15
16 opkg_index_cmd = bb.utils.which(os.getenv('PATH'), "opkg-make-index")
17 if self.d.getVar('PACKAGE_FEED_SIGN') == '1':
18 signer = get_signer(self.d, self.d.getVar('PACKAGE_FEED_GPG_BACKEND'))
19 else:
20 signer = None
21
22 if not os.path.exists(os.path.join(self.deploy_dir, "Packages")):
23 open(os.path.join(self.deploy_dir, "Packages"), "w").close()
24
25 index_cmds = set()
26 index_sign_files = set()
27 for arch_var in arch_vars:
28 archs = self.d.getVar(arch_var)
29 if archs is None:
30 continue
31
32 for arch in archs.split():
33 pkgs_dir = os.path.join(self.deploy_dir, arch)
34 pkgs_file = os.path.join(pkgs_dir, "Packages")
35
36 if not os.path.isdir(pkgs_dir):
37 continue
38
39 if not os.path.exists(pkgs_file):
40 open(pkgs_file, "w").close()
41
42 index_cmds.add('%s --checksum md5 --checksum sha256 -r %s -p %s -m %s' %
43 (opkg_index_cmd, pkgs_file, pkgs_file, pkgs_dir))
44
45 index_sign_files.add(pkgs_file)
46
47 if len(index_cmds) == 0:
48 bb.note("There are no packages in %s!" % self.deploy_dir)
49 return
50
51 oe.utils.multiprocess_launch(create_index, index_cmds, self.d)
52
53 if signer:
54 feed_sig_type = self.d.getVar('PACKAGE_FEED_GPG_SIGNATURE_TYPE')
55 is_ascii_sig = (feed_sig_type.upper() != "BIN")
56 for f in index_sign_files:
57 signer.detach_sign(f,
58 self.d.getVar('PACKAGE_FEED_GPG_NAME'),
59 self.d.getVar('PACKAGE_FEED_GPG_PASSPHRASE_FILE'),
60 armor=is_ascii_sig)
61
Andrew Geissler6ce62a22020-11-30 19:58:47 -060062class PMPkgsList(PkgsList):
63 def __init__(self, d, rootfs_dir):
64 super(PMPkgsList, self).__init__(d, rootfs_dir)
65 config_file = d.getVar("IPKGCONF_TARGET")
Andrew Geissler635e0e42020-08-21 15:58:33 -050066
67 self.opkg_cmd = bb.utils.which(os.getenv('PATH'), "opkg")
68 self.opkg_args = "-f %s -o %s " % (config_file, rootfs_dir)
69 self.opkg_args += self.d.getVar("OPKG_ARGS")
70
71 def list_pkgs(self, format=None):
72 cmd = "%s %s status" % (self.opkg_cmd, self.opkg_args)
73
74 # opkg returns success even when it printed some
75 # "Collected errors:" report to stderr. Mixing stderr into
76 # stdout then leads to random failures later on when
77 # parsing the output. To avoid this we need to collect both
78 # output streams separately and check for empty stderr.
79 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
80 cmd_output, cmd_stderr = p.communicate()
81 cmd_output = cmd_output.decode("utf-8")
82 cmd_stderr = cmd_stderr.decode("utf-8")
83 if p.returncode or cmd_stderr:
84 bb.fatal("Cannot get the installed packages list. Command '%s' "
85 "returned %d and stderr:\n%s" % (cmd, p.returncode, cmd_stderr))
86
87 return opkg_query(cmd_output)
88
89
90
91class OpkgDpkgPM(PackageManager):
92 def __init__(self, d, target_rootfs):
93 """
94 This is an abstract class. Do not instantiate this directly.
95 """
96 super(OpkgDpkgPM, self).__init__(d, target_rootfs)
97
98 def package_info(self, pkg, cmd):
99 """
100 Returns a dictionary with the package info.
101
102 This method extracts the common parts for Opkg and Dpkg
103 """
104
105 try:
106 output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True).decode("utf-8")
107 except subprocess.CalledProcessError as e:
108 bb.fatal("Unable to list available packages. Command '%s' "
109 "returned %d:\n%s" % (cmd, e.returncode, e.output.decode("utf-8")))
110 return opkg_query(output)
111
112 def extract(self, pkg, pkg_info):
113 """
114 Returns the path to a tmpdir where resides the contents of a package.
115
116 Deleting the tmpdir is responsability of the caller.
117
118 This method extracts the common parts for Opkg and Dpkg
119 """
120
121 ar_cmd = bb.utils.which(os.getenv("PATH"), "ar")
122 tar_cmd = bb.utils.which(os.getenv("PATH"), "tar")
123 pkg_path = pkg_info[pkg]["filepath"]
124
125 if not os.path.isfile(pkg_path):
126 bb.fatal("Unable to extract package for '%s'."
127 "File %s doesn't exists" % (pkg, pkg_path))
128
129 tmp_dir = tempfile.mkdtemp()
130 current_dir = os.getcwd()
131 os.chdir(tmp_dir)
132 data_tar = 'data.tar.xz'
133
134 try:
135 cmd = [ar_cmd, 'x', pkg_path]
136 output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
137 cmd = [tar_cmd, 'xf', data_tar]
138 output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
139 except subprocess.CalledProcessError as e:
140 bb.utils.remove(tmp_dir, recurse=True)
141 bb.fatal("Unable to extract %s package. Command '%s' "
142 "returned %d:\n%s" % (pkg_path, ' '.join(cmd), e.returncode, e.output.decode("utf-8")))
143 except OSError as e:
144 bb.utils.remove(tmp_dir, recurse=True)
145 bb.fatal("Unable to extract %s package. Command '%s' "
146 "returned %d:\n%s at %s" % (pkg_path, ' '.join(cmd), e.errno, e.strerror, e.filename))
147
148 bb.note("Extracted %s to %s" % (pkg_path, tmp_dir))
149 bb.utils.remove(os.path.join(tmp_dir, "debian-binary"))
150 bb.utils.remove(os.path.join(tmp_dir, "control.tar.gz"))
151 os.chdir(current_dir)
152
153 return tmp_dir
154
155 def _handle_intercept_failure(self, registered_pkgs):
156 self.mark_packages("unpacked", registered_pkgs.split())
157
158class OpkgPM(OpkgDpkgPM):
159 def __init__(self, d, target_rootfs, config_file, archs, task_name='target', ipk_repo_workdir="oe-rootfs-repo", filterbydependencies=True, prepare_index=True):
160 super(OpkgPM, self).__init__(d, target_rootfs)
161
162 self.config_file = config_file
163 self.pkg_archs = archs
164 self.task_name = task_name
165
166 self.deploy_dir = oe.path.join(self.d.getVar('WORKDIR'), ipk_repo_workdir)
167 self.deploy_lock_file = os.path.join(self.deploy_dir, "deploy.lock")
168 self.opkg_cmd = bb.utils.which(os.getenv('PATH'), "opkg")
169 self.opkg_args = "--volatile-cache -f %s -t %s -o %s " % (self.config_file, self.d.expand('${T}/ipktemp/') ,target_rootfs)
170 self.opkg_args += self.d.getVar("OPKG_ARGS")
171
172 if prepare_index:
173 create_packages_dir(self.d, self.deploy_dir, d.getVar("DEPLOY_DIR_IPK"), "package_write_ipk", filterbydependencies)
174
Andrew Geissler09209ee2020-12-13 08:44:15 -0600175 self.opkg_dir = oe.path.join(target_rootfs, self.d.getVar('OPKGLIBDIR'), "opkg")
Andrew Geissler635e0e42020-08-21 15:58:33 -0500176 bb.utils.mkdirhier(self.opkg_dir)
177
178 self.saved_opkg_dir = self.d.expand('${T}/saved/%s' % self.task_name)
179 if not os.path.exists(self.d.expand('${T}/saved')):
180 bb.utils.mkdirhier(self.d.expand('${T}/saved'))
181
182 self.from_feeds = (self.d.getVar('BUILD_IMAGES_FROM_FEEDS') or "") == "1"
183 if self.from_feeds:
184 self._create_custom_config()
185 else:
186 self._create_config()
187
188 self.indexer = OpkgIndexer(self.d, self.deploy_dir)
189
190 def mark_packages(self, status_tag, packages=None):
191 """
192 This function will change a package's status in /var/lib/opkg/status file.
193 If 'packages' is None then the new_status will be applied to all
194 packages
195 """
196 status_file = os.path.join(self.opkg_dir, "status")
197
198 with open(status_file, "r") as sf:
199 with open(status_file + ".tmp", "w+") as tmp_sf:
200 if packages is None:
201 tmp_sf.write(re.sub(r"Package: (.*?)\n((?:[^\n]+\n)*?)Status: (.*)(?:unpacked|installed)",
202 r"Package: \1\n\2Status: \3%s" % status_tag,
203 sf.read()))
204 else:
205 if type(packages).__name__ != "list":
206 raise TypeError("'packages' should be a list object")
207
208 status = sf.read()
209 for pkg in packages:
210 status = re.sub(r"Package: %s\n((?:[^\n]+\n)*?)Status: (.*)(?:unpacked|installed)" % pkg,
211 r"Package: %s\n\1Status: \2%s" % (pkg, status_tag),
212 status)
213
214 tmp_sf.write(status)
215
Andrew Geisslerc926e172021-05-07 16:11:35 -0500216 bb.utils.rename(status_file + ".tmp", status_file)
Andrew Geissler635e0e42020-08-21 15:58:33 -0500217
218 def _create_custom_config(self):
219 bb.note("Building from feeds activated!")
220
221 with open(self.config_file, "w+") as config_file:
222 priority = 1
223 for arch in self.pkg_archs.split():
224 config_file.write("arch %s %d\n" % (arch, priority))
225 priority += 5
226
227 for line in (self.d.getVar('IPK_FEED_URIS') or "").split():
228 feed_match = re.match(r"^[ \t]*(.*)##([^ \t]*)[ \t]*$", line)
229
230 if feed_match is not None:
231 feed_name = feed_match.group(1)
232 feed_uri = feed_match.group(2)
233
234 bb.note("Add %s feed with URL %s" % (feed_name, feed_uri))
235
236 config_file.write("src/gz %s %s\n" % (feed_name, feed_uri))
237
238 """
239 Allow to use package deploy directory contents as quick devel-testing
240 feed. This creates individual feed configs for each arch subdir of those
241 specified as compatible for the current machine.
242 NOTE: Development-helper feature, NOT a full-fledged feed.
243 """
244 if (self.d.getVar('FEED_DEPLOYDIR_BASE_URI') or "") != "":
245 for arch in self.pkg_archs.split():
246 cfg_file_name = os.path.join(self.target_rootfs,
247 self.d.getVar("sysconfdir"),
248 "opkg",
249 "local-%s-feed.conf" % arch)
250
251 with open(cfg_file_name, "w+") as cfg_file:
252 cfg_file.write("src/gz local-%s %s/%s" %
253 (arch,
254 self.d.getVar('FEED_DEPLOYDIR_BASE_URI'),
255 arch))
256
257 if self.d.getVar('OPKGLIBDIR') != '/var/lib':
258 # There is no command line option for this anymore, we need to add
259 # info_dir and status_file to config file, if OPKGLIBDIR doesn't have
260 # the default value of "/var/lib" as defined in opkg:
261 # libopkg/opkg_conf.h:#define OPKG_CONF_DEFAULT_LISTS_DIR VARDIR "/lib/opkg/lists"
262 # libopkg/opkg_conf.h:#define OPKG_CONF_DEFAULT_INFO_DIR VARDIR "/lib/opkg/info"
263 # libopkg/opkg_conf.h:#define OPKG_CONF_DEFAULT_STATUS_FILE VARDIR "/lib/opkg/status"
264 cfg_file.write("option info_dir %s\n" % os.path.join(self.d.getVar('OPKGLIBDIR'), 'opkg', 'info'))
265 cfg_file.write("option lists_dir %s\n" % os.path.join(self.d.getVar('OPKGLIBDIR'), 'opkg', 'lists'))
266 cfg_file.write("option status_file %s\n" % os.path.join(self.d.getVar('OPKGLIBDIR'), 'opkg', 'status'))
267
268
269 def _create_config(self):
270 with open(self.config_file, "w+") as config_file:
271 priority = 1
272 for arch in self.pkg_archs.split():
273 config_file.write("arch %s %d\n" % (arch, priority))
274 priority += 5
275
276 config_file.write("src oe file:%s\n" % self.deploy_dir)
277
278 for arch in self.pkg_archs.split():
279 pkgs_dir = os.path.join(self.deploy_dir, arch)
280 if os.path.isdir(pkgs_dir):
281 config_file.write("src oe-%s file:%s\n" %
282 (arch, pkgs_dir))
283
284 if self.d.getVar('OPKGLIBDIR') != '/var/lib':
285 # There is no command line option for this anymore, we need to add
286 # info_dir and status_file to config file, if OPKGLIBDIR doesn't have
287 # the default value of "/var/lib" as defined in opkg:
288 # libopkg/opkg_conf.h:#define OPKG_CONF_DEFAULT_LISTS_DIR VARDIR "/lib/opkg/lists"
289 # libopkg/opkg_conf.h:#define OPKG_CONF_DEFAULT_INFO_DIR VARDIR "/lib/opkg/info"
290 # libopkg/opkg_conf.h:#define OPKG_CONF_DEFAULT_STATUS_FILE VARDIR "/lib/opkg/status"
291 config_file.write("option info_dir %s\n" % os.path.join(self.d.getVar('OPKGLIBDIR'), 'opkg', 'info'))
292 config_file.write("option lists_dir %s\n" % os.path.join(self.d.getVar('OPKGLIBDIR'), 'opkg', 'lists'))
293 config_file.write("option status_file %s\n" % os.path.join(self.d.getVar('OPKGLIBDIR'), 'opkg', 'status'))
294
295 def insert_feeds_uris(self, feed_uris, feed_base_paths, feed_archs):
296 if feed_uris == "":
297 return
298
299 rootfs_config = os.path.join('%s/etc/opkg/base-feeds.conf'
300 % self.target_rootfs)
301
302 os.makedirs('%s/etc/opkg' % self.target_rootfs, exist_ok=True)
303
304 feed_uris = self.construct_uris(feed_uris.split(), feed_base_paths.split())
305 archs = self.pkg_archs.split() if feed_archs is None else feed_archs.split()
306
307 with open(rootfs_config, "w+") as config_file:
308 uri_iterator = 0
309 for uri in feed_uris:
310 if archs:
311 for arch in archs:
312 if (feed_archs is None) and (not os.path.exists(oe.path.join(self.deploy_dir, arch))):
313 continue
314 bb.note('Adding opkg feed url-%s-%d (%s)' %
315 (arch, uri_iterator, uri))
316 config_file.write("src/gz uri-%s-%d %s/%s\n" %
317 (arch, uri_iterator, uri, arch))
318 else:
319 bb.note('Adding opkg feed url-%d (%s)' %
320 (uri_iterator, uri))
321 config_file.write("src/gz uri-%d %s\n" %
322 (uri_iterator, uri))
323
324 uri_iterator += 1
325
326 def update(self):
327 self.deploy_dir_lock()
328
329 cmd = "%s %s update" % (self.opkg_cmd, self.opkg_args)
330
331 try:
332 subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT)
333 except subprocess.CalledProcessError as e:
334 self.deploy_dir_unlock()
335 bb.fatal("Unable to update the package index files. Command '%s' "
336 "returned %d:\n%s" % (cmd, e.returncode, e.output.decode("utf-8")))
337
338 self.deploy_dir_unlock()
339
Andrew Geissler615f2f12022-07-15 14:00:58 -0500340 def install(self, pkgs, attempt_only=False, hard_depends_only=False):
Andrew Geissler635e0e42020-08-21 15:58:33 -0500341 if not pkgs:
342 return
343
344 cmd = "%s %s" % (self.opkg_cmd, self.opkg_args)
345 for exclude in (self.d.getVar("PACKAGE_EXCLUDE") or "").split():
346 cmd += " --add-exclude %s" % exclude
347 for bad_recommendation in (self.d.getVar("BAD_RECOMMENDATIONS") or "").split():
348 cmd += " --add-ignore-recommends %s" % bad_recommendation
Andrew Geissler615f2f12022-07-15 14:00:58 -0500349 if hard_depends_only:
350 cmd += " --no-install-recommends"
Andrew Geissler635e0e42020-08-21 15:58:33 -0500351 cmd += " install "
352 cmd += " ".join(pkgs)
353
354 os.environ['D'] = self.target_rootfs
355 os.environ['OFFLINE_ROOT'] = self.target_rootfs
356 os.environ['IPKG_OFFLINE_ROOT'] = self.target_rootfs
357 os.environ['OPKG_OFFLINE_ROOT'] = self.target_rootfs
358 os.environ['INTERCEPT_DIR'] = self.intercepts_dir
359 os.environ['NATIVE_ROOT'] = self.d.getVar('STAGING_DIR_NATIVE')
360
361 try:
362 bb.note("Installing the following packages: %s" % ' '.join(pkgs))
363 bb.note(cmd)
364 output = subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT).decode("utf-8")
365 bb.note(output)
366 failed_pkgs = []
367 for line in output.split('\n'):
368 if line.endswith("configuration required on target."):
369 bb.warn(line)
370 failed_pkgs.append(line.split(".")[0])
371 if failed_pkgs:
372 failed_postinsts_abort(failed_pkgs, self.d.expand("${T}/log.do_${BB_CURRENTTASK}"))
373 except subprocess.CalledProcessError as e:
374 (bb.fatal, bb.warn)[attempt_only]("Unable to install packages. "
375 "Command '%s' returned %d:\n%s" %
376 (cmd, e.returncode, e.output.decode("utf-8")))
377
378 def remove(self, pkgs, with_dependencies=True):
379 if not pkgs:
380 return
381
382 if with_dependencies:
383 cmd = "%s %s --force-remove --force-removal-of-dependent-packages remove %s" % \
384 (self.opkg_cmd, self.opkg_args, ' '.join(pkgs))
385 else:
386 cmd = "%s %s --force-depends remove %s" % \
387 (self.opkg_cmd, self.opkg_args, ' '.join(pkgs))
388
389 try:
390 bb.note(cmd)
391 output = subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT).decode("utf-8")
392 bb.note(output)
393 except subprocess.CalledProcessError as e:
394 bb.fatal("Unable to remove packages. Command '%s' "
395 "returned %d:\n%s" % (e.cmd, e.returncode, e.output.decode("utf-8")))
396
397 def write_index(self):
398 self.deploy_dir_lock()
399
400 result = self.indexer.write_index()
401
402 self.deploy_dir_unlock()
403
404 if result is not None:
405 bb.fatal(result)
406
407 def remove_packaging_data(self):
Andrew Geissler09209ee2020-12-13 08:44:15 -0600408 cachedir = oe.path.join(self.target_rootfs, self.d.getVar("localstatedir"), "cache", "opkg")
Andrew Geissler635e0e42020-08-21 15:58:33 -0500409 bb.utils.remove(self.opkg_dir, True)
Andrew Geissler09209ee2020-12-13 08:44:15 -0600410 bb.utils.remove(cachedir, True)
Andrew Geissler635e0e42020-08-21 15:58:33 -0500411
412 def remove_lists(self):
413 if not self.from_feeds:
414 bb.utils.remove(os.path.join(self.opkg_dir, "lists"), True)
415
416 def list_installed(self):
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600417 return PMPkgsList(self.d, self.target_rootfs).list_pkgs()
Andrew Geissler635e0e42020-08-21 15:58:33 -0500418
419 def dummy_install(self, pkgs):
420 """
421 The following function dummy installs pkgs and returns the log of output.
422 """
423 if len(pkgs) == 0:
424 return
425
426 # Create an temp dir as opkg root for dummy installation
427 temp_rootfs = self.d.expand('${T}/opkg')
428 opkg_lib_dir = self.d.getVar('OPKGLIBDIR')
429 if opkg_lib_dir[0] == "/":
430 opkg_lib_dir = opkg_lib_dir[1:]
431 temp_opkg_dir = os.path.join(temp_rootfs, opkg_lib_dir, 'opkg')
432 bb.utils.mkdirhier(temp_opkg_dir)
433
434 opkg_args = "-f %s -o %s " % (self.config_file, temp_rootfs)
435 opkg_args += self.d.getVar("OPKG_ARGS")
436
437 cmd = "%s %s update" % (self.opkg_cmd, opkg_args)
438 try:
439 subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
440 except subprocess.CalledProcessError as e:
441 bb.fatal("Unable to update. Command '%s' "
442 "returned %d:\n%s" % (cmd, e.returncode, e.output.decode("utf-8")))
443
444 # Dummy installation
445 cmd = "%s %s --noaction install %s " % (self.opkg_cmd,
446 opkg_args,
447 ' '.join(pkgs))
448 try:
449 output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
450 except subprocess.CalledProcessError as e:
451 bb.fatal("Unable to dummy install packages. Command '%s' "
452 "returned %d:\n%s" % (cmd, e.returncode, e.output.decode("utf-8")))
453
454 bb.utils.remove(temp_rootfs, True)
455
456 return output
457
458 def backup_packaging_data(self):
459 # Save the opkglib for increment ipk image generation
460 if os.path.exists(self.saved_opkg_dir):
461 bb.utils.remove(self.saved_opkg_dir, True)
462 shutil.copytree(self.opkg_dir,
463 self.saved_opkg_dir,
464 symlinks=True)
465
466 def recover_packaging_data(self):
467 # Move the opkglib back
468 if os.path.exists(self.saved_opkg_dir):
469 if os.path.exists(self.opkg_dir):
470 bb.utils.remove(self.opkg_dir, True)
471
472 bb.note('Recover packaging data')
473 shutil.copytree(self.saved_opkg_dir,
474 self.opkg_dir,
475 symlinks=True)
476
477 def package_info(self, pkg):
478 """
479 Returns a dictionary with the package info.
480 """
481 cmd = "%s %s info %s" % (self.opkg_cmd, self.opkg_args, pkg)
482 pkg_info = super(OpkgPM, self).package_info(pkg, cmd)
483
484 pkg_arch = pkg_info[pkg]["arch"]
485 pkg_filename = pkg_info[pkg]["filename"]
486 pkg_info[pkg]["filepath"] = \
487 os.path.join(self.deploy_dir, pkg_arch, pkg_filename)
488
489 return pkg_info
490
491 def extract(self, pkg):
492 """
493 Returns the path to a tmpdir where resides the contents of a package.
494
495 Deleting the tmpdir is responsability of the caller.
496 """
497 pkg_info = self.package_info(pkg)
498 if not pkg_info:
499 bb.fatal("Unable to get information for package '%s' while "
500 "trying to extract the package." % pkg)
501
502 tmp_dir = super(OpkgPM, self).extract(pkg, pkg_info)
503 bb.utils.remove(os.path.join(tmp_dir, "data.tar.xz"))
504
505 return tmp_dir