rootfs.py 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  1. #
  2. # SPDX-License-Identifier: GPL-2.0-only
  3. #
  4. from abc import ABCMeta, abstractmethod
  5. from oe.utils import execute_pre_post_process
  6. from oe.package_manager import *
  7. from oe.manifest import *
  8. import oe.path
  9. import filecmp
  10. import shutil
  11. import os
  12. import subprocess
  13. import re
  14. class Rootfs(object, metaclass=ABCMeta):
  15. """
  16. This is an abstract class. Do not instantiate this directly.
  17. """
  18. def __init__(self, d, progress_reporter=None, logcatcher=None):
  19. self.d = d
  20. self.pm = None
  21. self.image_rootfs = self.d.getVar('IMAGE_ROOTFS')
  22. self.deploydir = self.d.getVar('IMGDEPLOYDIR')
  23. self.progress_reporter = progress_reporter
  24. self.logcatcher = logcatcher
  25. self.install_order = Manifest.INSTALL_ORDER
  26. @abstractmethod
  27. def _create(self):
  28. pass
  29. @abstractmethod
  30. def _get_delayed_postinsts(self):
  31. pass
  32. @abstractmethod
  33. def _save_postinsts(self):
  34. pass
  35. @abstractmethod
  36. def _log_check(self):
  37. pass
  38. def _log_check_common(self, type, match):
  39. # Ignore any lines containing log_check to avoid recursion, and ignore
  40. # lines beginning with a + since sh -x may emit code which isn't
  41. # actually executed, but may contain error messages
  42. excludes = [ 'log_check', r'^\+' ]
  43. if hasattr(self, 'log_check_expected_regexes'):
  44. excludes.extend(self.log_check_expected_regexes)
  45. excludes = [re.compile(x) for x in excludes]
  46. r = re.compile(match)
  47. log_path = self.d.expand("${T}/log.do_rootfs")
  48. messages = []
  49. with open(log_path, 'r') as log:
  50. for line in log:
  51. if self.logcatcher and self.logcatcher.contains(line.rstrip()):
  52. continue
  53. for ee in excludes:
  54. m = ee.search(line)
  55. if m:
  56. break
  57. if m:
  58. continue
  59. m = r.search(line)
  60. if m:
  61. messages.append('[log_check] %s' % line)
  62. if messages:
  63. if len(messages) == 1:
  64. msg = '1 %s message' % type
  65. else:
  66. msg = '%d %s messages' % (len(messages), type)
  67. msg = '[log_check] %s: found %s in the logfile:\n%s' % \
  68. (self.d.getVar('PN'), msg, ''.join(messages))
  69. if type == 'error':
  70. bb.fatal(msg)
  71. else:
  72. bb.warn(msg)
  73. def _log_check_warn(self):
  74. self._log_check_common('warning', '^(warn|Warn|WARNING:)')
  75. def _log_check_error(self):
  76. self._log_check_common('error', self.log_check_regex)
  77. def _insert_feed_uris(self):
  78. if bb.utils.contains("IMAGE_FEATURES", "package-management",
  79. True, False, self.d):
  80. self.pm.insert_feeds_uris(self.d.getVar('PACKAGE_FEED_URIS') or "",
  81. self.d.getVar('PACKAGE_FEED_BASE_PATHS') or "",
  82. self.d.getVar('PACKAGE_FEED_ARCHS'))
  83. """
  84. The _cleanup() method should be used to clean-up stuff that we don't really
  85. want to end up on target. For example, in the case of RPM, the DB locks.
  86. The method is called, once, at the end of create() method.
  87. """
  88. @abstractmethod
  89. def _cleanup(self):
  90. pass
  91. def _setup_dbg_rootfs(self, dirs):
  92. gen_debugfs = self.d.getVar('IMAGE_GEN_DEBUGFS') or '0'
  93. if gen_debugfs != '1':
  94. return
  95. bb.note(" Renaming the original rootfs...")
  96. try:
  97. shutil.rmtree(self.image_rootfs + '-orig')
  98. except:
  99. pass
  100. os.rename(self.image_rootfs, self.image_rootfs + '-orig')
  101. bb.note(" Creating debug rootfs...")
  102. bb.utils.mkdirhier(self.image_rootfs)
  103. bb.note(" Copying back package database...")
  104. for dir in dirs:
  105. if not os.path.isdir(self.image_rootfs + '-orig' + dir):
  106. continue
  107. bb.utils.mkdirhier(self.image_rootfs + os.path.dirname(dir))
  108. shutil.copytree(self.image_rootfs + '-orig' + dir, self.image_rootfs + dir, symlinks=True)
  109. cpath = oe.cachedpath.CachedPath()
  110. # Copy files located in /usr/lib/debug or /usr/src/debug
  111. for dir in ["/usr/lib/debug", "/usr/src/debug"]:
  112. src = self.image_rootfs + '-orig' + dir
  113. if cpath.exists(src):
  114. dst = self.image_rootfs + dir
  115. bb.utils.mkdirhier(os.path.dirname(dst))
  116. shutil.copytree(src, dst)
  117. # Copy files with suffix '.debug' or located in '.debug' dir.
  118. for root, dirs, files in cpath.walk(self.image_rootfs + '-orig'):
  119. relative_dir = root[len(self.image_rootfs + '-orig'):]
  120. for f in files:
  121. if f.endswith('.debug') or '/.debug' in relative_dir:
  122. bb.utils.mkdirhier(self.image_rootfs + relative_dir)
  123. shutil.copy(os.path.join(root, f),
  124. self.image_rootfs + relative_dir)
  125. bb.note(" Install complementary '*-dbg' packages...")
  126. self.pm.install_complementary('*-dbg')
  127. if self.d.getVar('PACKAGE_DEBUG_SPLIT_STYLE') == 'debug-with-srcpkg':
  128. bb.note(" Install complementary '*-src' packages...")
  129. self.pm.install_complementary('*-src')
  130. """
  131. Install additional debug packages. Possibility to install additional packages,
  132. which are not automatically installed as complementary package of
  133. standard one, e.g. debug package of static libraries.
  134. """
  135. extra_debug_pkgs = self.d.getVar('IMAGE_INSTALL_DEBUGFS')
  136. if extra_debug_pkgs:
  137. bb.note(" Install extra debug packages...")
  138. self.pm.install(extra_debug_pkgs.split(), True)
  139. bb.note(" Rename debug rootfs...")
  140. try:
  141. shutil.rmtree(self.image_rootfs + '-dbg')
  142. except:
  143. pass
  144. os.rename(self.image_rootfs, self.image_rootfs + '-dbg')
  145. bb.note(" Restoreing original rootfs...")
  146. os.rename(self.image_rootfs + '-orig', self.image_rootfs)
  147. def _exec_shell_cmd(self, cmd):
  148. fakerootcmd = self.d.getVar('FAKEROOT')
  149. if fakerootcmd is not None:
  150. exec_cmd = [fakerootcmd, cmd]
  151. else:
  152. exec_cmd = cmd
  153. try:
  154. subprocess.check_output(exec_cmd, stderr=subprocess.STDOUT)
  155. except subprocess.CalledProcessError as e:
  156. return("Command '%s' returned %d:\n%s" % (e.cmd, e.returncode, e.output))
  157. return None
  158. def create(self):
  159. bb.note("###### Generate rootfs #######")
  160. pre_process_cmds = self.d.getVar("ROOTFS_PREPROCESS_COMMAND")
  161. post_process_cmds = self.d.getVar("ROOTFS_POSTPROCESS_COMMAND")
  162. rootfs_post_install_cmds = self.d.getVar('ROOTFS_POSTINSTALL_COMMAND')
  163. bb.utils.mkdirhier(self.image_rootfs)
  164. bb.utils.mkdirhier(self.deploydir)
  165. execute_pre_post_process(self.d, pre_process_cmds)
  166. if self.progress_reporter:
  167. self.progress_reporter.next_stage()
  168. # call the package manager dependent create method
  169. self._create()
  170. sysconfdir = self.image_rootfs + self.d.getVar('sysconfdir')
  171. bb.utils.mkdirhier(sysconfdir)
  172. with open(sysconfdir + "/version", "w+") as ver:
  173. ver.write(self.d.getVar('BUILDNAME') + "\n")
  174. execute_pre_post_process(self.d, rootfs_post_install_cmds)
  175. self.pm.run_intercepts()
  176. execute_pre_post_process(self.d, post_process_cmds)
  177. if self.progress_reporter:
  178. self.progress_reporter.next_stage()
  179. if bb.utils.contains("IMAGE_FEATURES", "read-only-rootfs",
  180. True, False, self.d):
  181. delayed_postinsts = self._get_delayed_postinsts()
  182. if delayed_postinsts is not None:
  183. bb.fatal("The following packages could not be configured "
  184. "offline and rootfs is read-only: %s" %
  185. delayed_postinsts)
  186. if self.d.getVar('USE_DEVFS') != "1":
  187. self._create_devfs()
  188. self._uninstall_unneeded()
  189. if self.progress_reporter:
  190. self.progress_reporter.next_stage()
  191. self._insert_feed_uris()
  192. self._run_ldconfig()
  193. if self.d.getVar('USE_DEPMOD') != "0":
  194. self._generate_kernel_module_deps()
  195. self._cleanup()
  196. self._log_check()
  197. if self.progress_reporter:
  198. self.progress_reporter.next_stage()
  199. def _uninstall_unneeded(self):
  200. # Remove unneeded init script symlinks
  201. delayed_postinsts = self._get_delayed_postinsts()
  202. if delayed_postinsts is None:
  203. if os.path.exists(self.d.expand("${IMAGE_ROOTFS}${sysconfdir}/init.d/run-postinsts")):
  204. self._exec_shell_cmd(["update-rc.d", "-f", "-r",
  205. self.d.getVar('IMAGE_ROOTFS'),
  206. "run-postinsts", "remove"])
  207. image_rorfs = bb.utils.contains("IMAGE_FEATURES", "read-only-rootfs",
  208. True, False, self.d)
  209. image_rorfs_force = self.d.getVar('FORCE_RO_REMOVE')
  210. if image_rorfs or image_rorfs_force == "1":
  211. # Remove components that we don't need if it's a read-only rootfs
  212. unneeded_pkgs = self.d.getVar("ROOTFS_RO_UNNEEDED").split()
  213. pkgs_installed = image_list_installed_packages(self.d)
  214. # Make sure update-alternatives is removed last. This is
  215. # because its database has to available while uninstalling
  216. # other packages, allowing alternative symlinks of packages
  217. # to be uninstalled or to be managed correctly otherwise.
  218. provider = self.d.getVar("VIRTUAL-RUNTIME_update-alternatives")
  219. pkgs_to_remove = sorted([pkg for pkg in pkgs_installed if pkg in unneeded_pkgs], key=lambda x: x == provider)
  220. # update-alternatives provider is removed in its own remove()
  221. # call because all package managers do not guarantee the packages
  222. # are removed in the order they given in the list (which is
  223. # passed to the command line). The sorting done earlier is
  224. # utilized to implement the 2-stage removal.
  225. if len(pkgs_to_remove) > 1:
  226. self.pm.remove(pkgs_to_remove[:-1], False)
  227. if len(pkgs_to_remove) > 0:
  228. self.pm.remove([pkgs_to_remove[-1]], False)
  229. if delayed_postinsts:
  230. self._save_postinsts()
  231. if image_rorfs:
  232. bb.warn("There are post install scripts "
  233. "in a read-only rootfs")
  234. post_uninstall_cmds = self.d.getVar("ROOTFS_POSTUNINSTALL_COMMAND")
  235. execute_pre_post_process(self.d, post_uninstall_cmds)
  236. runtime_pkgmanage = bb.utils.contains("IMAGE_FEATURES", "package-management",
  237. True, False, self.d)
  238. if not runtime_pkgmanage:
  239. # Remove the package manager data files
  240. self.pm.remove_packaging_data()
  241. def _run_ldconfig(self):
  242. if self.d.getVar('LDCONFIGDEPEND'):
  243. bb.note("Executing: ldconfig -r" + self.image_rootfs + "-c new -v")
  244. self._exec_shell_cmd(['ldconfig', '-r', self.image_rootfs, '-c',
  245. 'new', '-v'])
  246. def _check_for_kernel_modules(self, modules_dir):
  247. for root, dirs, files in os.walk(modules_dir, topdown=True):
  248. for name in files:
  249. found_ko = name.endswith(".ko")
  250. if found_ko:
  251. return found_ko
  252. return False
  253. def _generate_kernel_module_deps(self):
  254. modules_dir = os.path.join(self.image_rootfs, 'lib', 'modules')
  255. # if we don't have any modules don't bother to do the depmod
  256. if not self._check_for_kernel_modules(modules_dir):
  257. bb.note("No Kernel Modules found, not running depmod")
  258. return
  259. kernel_abi_ver_file = oe.path.join(self.d.getVar('PKGDATA_DIR'), "kernel-depmod",
  260. 'kernel-abiversion')
  261. if not os.path.exists(kernel_abi_ver_file):
  262. bb.fatal("No kernel-abiversion file found (%s), cannot run depmod, aborting" % kernel_abi_ver_file)
  263. kernel_ver = open(kernel_abi_ver_file).read().strip(' \n')
  264. versioned_modules_dir = os.path.join(self.image_rootfs, modules_dir, kernel_ver)
  265. bb.utils.mkdirhier(versioned_modules_dir)
  266. self._exec_shell_cmd(['depmodwrapper', '-a', '-b', self.image_rootfs, kernel_ver])
  267. """
  268. Create devfs:
  269. * IMAGE_DEVICE_TABLE is the old name to an absolute path to a device table file
  270. * IMAGE_DEVICE_TABLES is a new name for a file, or list of files, seached
  271. for in the BBPATH
  272. If neither are specified then the default name of files/device_table-minimal.txt
  273. is searched for in the BBPATH (same as the old version.)
  274. """
  275. def _create_devfs(self):
  276. devtable_list = []
  277. devtable = self.d.getVar('IMAGE_DEVICE_TABLE')
  278. if devtable is not None:
  279. devtable_list.append(devtable)
  280. else:
  281. devtables = self.d.getVar('IMAGE_DEVICE_TABLES')
  282. if devtables is None:
  283. devtables = 'files/device_table-minimal.txt'
  284. for devtable in devtables.split():
  285. devtable_list.append("%s" % bb.utils.which(self.d.getVar('BBPATH'), devtable))
  286. for devtable in devtable_list:
  287. self._exec_shell_cmd(["makedevs", "-r",
  288. self.image_rootfs, "-D", devtable])
  289. class RpmRootfs(Rootfs):
  290. def __init__(self, d, manifest_dir, progress_reporter=None, logcatcher=None):
  291. super(RpmRootfs, self).__init__(d, progress_reporter, logcatcher)
  292. self.log_check_regex = r'(unpacking of archive failed|Cannot find package'\
  293. r'|exit 1|ERROR: |Error: |Error |ERROR '\
  294. r'|Failed |Failed: |Failed$|Failed\(\d+\):)'
  295. self.manifest = RpmManifest(d, manifest_dir)
  296. self.pm = RpmPM(d,
  297. d.getVar('IMAGE_ROOTFS'),
  298. self.d.getVar('TARGET_VENDOR')
  299. )
  300. self.inc_rpm_image_gen = self.d.getVar('INC_RPM_IMAGE_GEN')
  301. if self.inc_rpm_image_gen != "1":
  302. bb.utils.remove(self.image_rootfs, True)
  303. else:
  304. self.pm.recovery_packaging_data()
  305. bb.utils.remove(self.d.getVar('MULTILIB_TEMP_ROOTFS'), True)
  306. self.pm.create_configs()
  307. '''
  308. While rpm incremental image generation is enabled, it will remove the
  309. unneeded pkgs by comparing the new install solution manifest and the
  310. old installed manifest.
  311. '''
  312. def _create_incremental(self, pkgs_initial_install):
  313. if self.inc_rpm_image_gen == "1":
  314. pkgs_to_install = list()
  315. for pkg_type in pkgs_initial_install:
  316. pkgs_to_install += pkgs_initial_install[pkg_type]
  317. installed_manifest = self.pm.load_old_install_solution()
  318. solution_manifest = self.pm.dump_install_solution(pkgs_to_install)
  319. pkg_to_remove = list()
  320. for pkg in installed_manifest:
  321. if pkg not in solution_manifest:
  322. pkg_to_remove.append(pkg)
  323. self.pm.update()
  324. bb.note('incremental update -- upgrade packages in place ')
  325. self.pm.upgrade()
  326. if pkg_to_remove != []:
  327. bb.note('incremental removed: %s' % ' '.join(pkg_to_remove))
  328. self.pm.remove(pkg_to_remove)
  329. self.pm.autoremove()
  330. def _create(self):
  331. pkgs_to_install = self.manifest.parse_initial_manifest()
  332. rpm_pre_process_cmds = self.d.getVar('RPM_PREPROCESS_COMMANDS')
  333. rpm_post_process_cmds = self.d.getVar('RPM_POSTPROCESS_COMMANDS')
  334. # update PM index files
  335. self.pm.write_index()
  336. execute_pre_post_process(self.d, rpm_pre_process_cmds)
  337. if self.progress_reporter:
  338. self.progress_reporter.next_stage()
  339. if self.inc_rpm_image_gen == "1":
  340. self._create_incremental(pkgs_to_install)
  341. if self.progress_reporter:
  342. self.progress_reporter.next_stage()
  343. self.pm.update()
  344. pkgs = []
  345. pkgs_attempt = []
  346. for pkg_type in pkgs_to_install:
  347. if pkg_type == Manifest.PKG_TYPE_ATTEMPT_ONLY:
  348. pkgs_attempt += pkgs_to_install[pkg_type]
  349. else:
  350. pkgs += pkgs_to_install[pkg_type]
  351. if self.progress_reporter:
  352. self.progress_reporter.next_stage()
  353. self.pm.install(pkgs)
  354. if self.progress_reporter:
  355. self.progress_reporter.next_stage()
  356. self.pm.install(pkgs_attempt, True)
  357. if self.progress_reporter:
  358. self.progress_reporter.next_stage()
  359. self.pm.install_complementary()
  360. if self.progress_reporter:
  361. self.progress_reporter.next_stage()
  362. self._setup_dbg_rootfs(['/etc', '/var/lib/rpm', '/var/cache/dnf', '/var/lib/dnf'])
  363. execute_pre_post_process(self.d, rpm_post_process_cmds)
  364. if self.inc_rpm_image_gen == "1":
  365. self.pm.backup_packaging_data()
  366. if self.progress_reporter:
  367. self.progress_reporter.next_stage()
  368. @staticmethod
  369. def _depends_list():
  370. return ['DEPLOY_DIR_RPM', 'INC_RPM_IMAGE_GEN', 'RPM_PREPROCESS_COMMANDS',
  371. 'RPM_POSTPROCESS_COMMANDS', 'RPM_PREFER_ELF_ARCH']
  372. def _get_delayed_postinsts(self):
  373. postinst_dir = self.d.expand("${IMAGE_ROOTFS}${sysconfdir}/rpm-postinsts")
  374. if os.path.isdir(postinst_dir):
  375. files = os.listdir(postinst_dir)
  376. for f in files:
  377. bb.note('Delayed package scriptlet: %s' % f)
  378. return files
  379. return None
  380. def _save_postinsts(self):
  381. # this is just a stub. For RPM, the failed postinstalls are
  382. # already saved in /etc/rpm-postinsts
  383. pass
  384. def _log_check(self):
  385. self._log_check_warn()
  386. self._log_check_error()
  387. def _cleanup(self):
  388. if bb.utils.contains("IMAGE_FEATURES", "package-management", True, False, self.d):
  389. self.pm._invoke_dnf(["clean", "all"])
  390. class DpkgOpkgRootfs(Rootfs):
  391. def __init__(self, d, progress_reporter=None, logcatcher=None):
  392. super(DpkgOpkgRootfs, self).__init__(d, progress_reporter, logcatcher)
  393. def _get_pkgs_postinsts(self, status_file):
  394. def _get_pkg_depends_list(pkg_depends):
  395. pkg_depends_list = []
  396. # filter version requirements like libc (>= 1.1)
  397. for dep in pkg_depends.split(', '):
  398. m_dep = re.match(r"^(.*) \(.*\)$", dep)
  399. if m_dep:
  400. dep = m_dep.group(1)
  401. pkg_depends_list.append(dep)
  402. return pkg_depends_list
  403. pkgs = {}
  404. pkg_name = ""
  405. pkg_status_match = False
  406. pkg_depends = ""
  407. with open(status_file) as status:
  408. data = status.read()
  409. status.close()
  410. for line in data.split('\n'):
  411. m_pkg = re.match(r"^Package: (.*)", line)
  412. m_status = re.match(r"^Status:.*unpacked", line)
  413. m_depends = re.match(r"^Depends: (.*)", line)
  414. #Only one of m_pkg, m_status or m_depends is not None at time
  415. #If m_pkg is not None, we started a new package
  416. if m_pkg is not None:
  417. #Get Package name
  418. pkg_name = m_pkg.group(1)
  419. #Make sure we reset other variables
  420. pkg_status_match = False
  421. pkg_depends = ""
  422. elif m_status is not None:
  423. #New status matched
  424. pkg_status_match = True
  425. elif m_depends is not None:
  426. #New depends macthed
  427. pkg_depends = m_depends.group(1)
  428. else:
  429. pass
  430. #Now check if we can process package depends and postinst
  431. if "" != pkg_name and pkg_status_match:
  432. pkgs[pkg_name] = _get_pkg_depends_list(pkg_depends)
  433. else:
  434. #Not enough information
  435. pass
  436. # remove package dependencies not in postinsts
  437. pkg_names = list(pkgs.keys())
  438. for pkg_name in pkg_names:
  439. deps = pkgs[pkg_name][:]
  440. for d in deps:
  441. if d not in pkg_names:
  442. pkgs[pkg_name].remove(d)
  443. return pkgs
  444. def _get_delayed_postinsts_common(self, status_file):
  445. def _dep_resolve(graph, node, resolved, seen):
  446. seen.append(node)
  447. for edge in graph[node]:
  448. if edge not in resolved:
  449. if edge in seen:
  450. raise RuntimeError("Packages %s and %s have " \
  451. "a circular dependency in postinsts scripts." \
  452. % (node, edge))
  453. _dep_resolve(graph, edge, resolved, seen)
  454. resolved.append(node)
  455. pkg_list = []
  456. pkgs = None
  457. if not self.d.getVar('PACKAGE_INSTALL').strip():
  458. bb.note("Building empty image")
  459. else:
  460. pkgs = self._get_pkgs_postinsts(status_file)
  461. if pkgs:
  462. root = "__packagegroup_postinst__"
  463. pkgs[root] = list(pkgs.keys())
  464. _dep_resolve(pkgs, root, pkg_list, [])
  465. pkg_list.remove(root)
  466. if len(pkg_list) == 0:
  467. return None
  468. return pkg_list
  469. def _save_postinsts_common(self, dst_postinst_dir, src_postinst_dir):
  470. if bb.utils.contains("IMAGE_FEATURES", "package-management",
  471. True, False, self.d):
  472. return
  473. num = 0
  474. for p in self._get_delayed_postinsts():
  475. bb.utils.mkdirhier(dst_postinst_dir)
  476. if os.path.exists(os.path.join(src_postinst_dir, p + ".postinst")):
  477. shutil.copy(os.path.join(src_postinst_dir, p + ".postinst"),
  478. os.path.join(dst_postinst_dir, "%03d-%s" % (num, p)))
  479. num += 1
  480. class DpkgRootfs(DpkgOpkgRootfs):
  481. def __init__(self, d, manifest_dir, progress_reporter=None, logcatcher=None):
  482. super(DpkgRootfs, self).__init__(d, progress_reporter, logcatcher)
  483. self.log_check_regex = '^E:'
  484. self.log_check_expected_regexes = \
  485. [
  486. "^E: Unmet dependencies."
  487. ]
  488. bb.utils.remove(self.image_rootfs, True)
  489. bb.utils.remove(self.d.getVar('MULTILIB_TEMP_ROOTFS'), True)
  490. self.manifest = DpkgManifest(d, manifest_dir)
  491. self.pm = DpkgPM(d, d.getVar('IMAGE_ROOTFS'),
  492. d.getVar('PACKAGE_ARCHS'),
  493. d.getVar('DPKG_ARCH'))
  494. def _create(self):
  495. pkgs_to_install = self.manifest.parse_initial_manifest()
  496. deb_pre_process_cmds = self.d.getVar('DEB_PREPROCESS_COMMANDS')
  497. deb_post_process_cmds = self.d.getVar('DEB_POSTPROCESS_COMMANDS')
  498. alt_dir = self.d.expand("${IMAGE_ROOTFS}/var/lib/dpkg/alternatives")
  499. bb.utils.mkdirhier(alt_dir)
  500. # update PM index files
  501. self.pm.write_index()
  502. execute_pre_post_process(self.d, deb_pre_process_cmds)
  503. if self.progress_reporter:
  504. self.progress_reporter.next_stage()
  505. # Don't support incremental, so skip that
  506. self.progress_reporter.next_stage()
  507. self.pm.update()
  508. if self.progress_reporter:
  509. self.progress_reporter.next_stage()
  510. for pkg_type in self.install_order:
  511. if pkg_type in pkgs_to_install:
  512. self.pm.install(pkgs_to_install[pkg_type],
  513. [False, True][pkg_type == Manifest.PKG_TYPE_ATTEMPT_ONLY])
  514. if self.progress_reporter:
  515. # Don't support attemptonly, so skip that
  516. self.progress_reporter.next_stage()
  517. self.progress_reporter.next_stage()
  518. self.pm.install_complementary()
  519. if self.progress_reporter:
  520. self.progress_reporter.next_stage()
  521. self._setup_dbg_rootfs(['/var/lib/dpkg'])
  522. self.pm.fix_broken_dependencies()
  523. self.pm.mark_packages("installed")
  524. self.pm.run_pre_post_installs()
  525. execute_pre_post_process(self.d, deb_post_process_cmds)
  526. if self.progress_reporter:
  527. self.progress_reporter.next_stage()
  528. @staticmethod
  529. def _depends_list():
  530. return ['DEPLOY_DIR_DEB', 'DEB_SDK_ARCH', 'APTCONF_TARGET', 'APT_ARGS', 'DPKG_ARCH', 'DEB_PREPROCESS_COMMANDS', 'DEB_POSTPROCESS_COMMANDS']
  531. def _get_delayed_postinsts(self):
  532. status_file = self.image_rootfs + "/var/lib/dpkg/status"
  533. return self._get_delayed_postinsts_common(status_file)
  534. def _save_postinsts(self):
  535. dst_postinst_dir = self.d.expand("${IMAGE_ROOTFS}${sysconfdir}/deb-postinsts")
  536. src_postinst_dir = self.d.expand("${IMAGE_ROOTFS}/var/lib/dpkg/info")
  537. return self._save_postinsts_common(dst_postinst_dir, src_postinst_dir)
  538. def _log_check(self):
  539. self._log_check_warn()
  540. self._log_check_error()
  541. def _cleanup(self):
  542. pass
  543. class OpkgRootfs(DpkgOpkgRootfs):
  544. def __init__(self, d, manifest_dir, progress_reporter=None, logcatcher=None):
  545. super(OpkgRootfs, self).__init__(d, progress_reporter, logcatcher)
  546. self.log_check_regex = '(exit 1|Collected errors)'
  547. self.manifest = OpkgManifest(d, manifest_dir)
  548. self.opkg_conf = self.d.getVar("IPKGCONF_TARGET")
  549. self.pkg_archs = self.d.getVar("ALL_MULTILIB_PACKAGE_ARCHS")
  550. self.inc_opkg_image_gen = self.d.getVar('INC_IPK_IMAGE_GEN') or ""
  551. if self._remove_old_rootfs():
  552. bb.utils.remove(self.image_rootfs, True)
  553. self.pm = OpkgPM(d,
  554. self.image_rootfs,
  555. self.opkg_conf,
  556. self.pkg_archs)
  557. else:
  558. self.pm = OpkgPM(d,
  559. self.image_rootfs,
  560. self.opkg_conf,
  561. self.pkg_archs)
  562. self.pm.recover_packaging_data()
  563. bb.utils.remove(self.d.getVar('MULTILIB_TEMP_ROOTFS'), True)
  564. def _prelink_file(self, root_dir, filename):
  565. bb.note('prelink %s in %s' % (filename, root_dir))
  566. prelink_cfg = oe.path.join(root_dir,
  567. self.d.expand('${sysconfdir}/prelink.conf'))
  568. if not os.path.exists(prelink_cfg):
  569. shutil.copy(self.d.expand('${STAGING_DIR_NATIVE}${sysconfdir_native}/prelink.conf'),
  570. prelink_cfg)
  571. cmd_prelink = self.d.expand('${STAGING_DIR_NATIVE}${sbindir_native}/prelink')
  572. self._exec_shell_cmd([cmd_prelink,
  573. '--root',
  574. root_dir,
  575. '-amR',
  576. '-N',
  577. '-c',
  578. self.d.expand('${sysconfdir}/prelink.conf')])
  579. '''
  580. Compare two files with the same key twice to see if they are equal.
  581. If they are not equal, it means they are duplicated and come from
  582. different packages.
  583. 1st: Comapre them directly;
  584. 2nd: While incremental image creation is enabled, one of the
  585. files could be probaly prelinked in the previous image
  586. creation and the file has been changed, so we need to
  587. prelink the other one and compare them.
  588. '''
  589. def _file_equal(self, key, f1, f2):
  590. # Both of them are not prelinked
  591. if filecmp.cmp(f1, f2):
  592. return True
  593. if bb.data.inherits_class('image-prelink', self.d):
  594. if self.image_rootfs not in f1:
  595. self._prelink_file(f1.replace(key, ''), f1)
  596. if self.image_rootfs not in f2:
  597. self._prelink_file(f2.replace(key, ''), f2)
  598. # Both of them are prelinked
  599. if filecmp.cmp(f1, f2):
  600. return True
  601. # Not equal
  602. return False
  603. """
  604. This function was reused from the old implementation.
  605. See commit: "image.bbclass: Added variables for multilib support." by
  606. Lianhao Lu.
  607. """
  608. def _multilib_sanity_test(self, dirs):
  609. allow_replace = self.d.getVar("MULTILIBRE_ALLOW_REP")
  610. if allow_replace is None:
  611. allow_replace = ""
  612. allow_rep = re.compile(re.sub(r"\|$", r"", allow_replace))
  613. error_prompt = "Multilib check error:"
  614. files = {}
  615. for dir in dirs:
  616. for root, subfolders, subfiles in os.walk(dir):
  617. for file in subfiles:
  618. item = os.path.join(root, file)
  619. key = str(os.path.join("/", os.path.relpath(item, dir)))
  620. valid = True
  621. if key in files:
  622. #check whether the file is allow to replace
  623. if allow_rep.match(key):
  624. valid = True
  625. else:
  626. if os.path.exists(files[key]) and \
  627. os.path.exists(item) and \
  628. not self._file_equal(key, files[key], item):
  629. valid = False
  630. bb.fatal("%s duplicate files %s %s is not the same\n" %
  631. (error_prompt, item, files[key]))
  632. #pass the check, add to list
  633. if valid:
  634. files[key] = item
  635. def _multilib_test_install(self, pkgs):
  636. ml_temp = self.d.getVar("MULTILIB_TEMP_ROOTFS")
  637. bb.utils.mkdirhier(ml_temp)
  638. dirs = [self.image_rootfs]
  639. for variant in self.d.getVar("MULTILIB_VARIANTS").split():
  640. ml_target_rootfs = os.path.join(ml_temp, variant)
  641. bb.utils.remove(ml_target_rootfs, True)
  642. ml_opkg_conf = os.path.join(ml_temp,
  643. variant + "-" + os.path.basename(self.opkg_conf))
  644. ml_pm = OpkgPM(self.d, ml_target_rootfs, ml_opkg_conf, self.pkg_archs, prepare_index=False)
  645. ml_pm.update()
  646. ml_pm.install(pkgs)
  647. dirs.append(ml_target_rootfs)
  648. self._multilib_sanity_test(dirs)
  649. '''
  650. While ipk incremental image generation is enabled, it will remove the
  651. unneeded pkgs by comparing the old full manifest in previous existing
  652. image and the new full manifest in the current image.
  653. '''
  654. def _remove_extra_packages(self, pkgs_initial_install):
  655. if self.inc_opkg_image_gen == "1":
  656. # Parse full manifest in previous existing image creation session
  657. old_full_manifest = self.manifest.parse_full_manifest()
  658. # Create full manifest for the current image session, the old one
  659. # will be replaced by the new one.
  660. self.manifest.create_full(self.pm)
  661. # Parse full manifest in current image creation session
  662. new_full_manifest = self.manifest.parse_full_manifest()
  663. pkg_to_remove = list()
  664. for pkg in old_full_manifest:
  665. if pkg not in new_full_manifest:
  666. pkg_to_remove.append(pkg)
  667. if pkg_to_remove != []:
  668. bb.note('decremental removed: %s' % ' '.join(pkg_to_remove))
  669. self.pm.remove(pkg_to_remove)
  670. '''
  671. Compare with previous existing image creation, if some conditions
  672. triggered, the previous old image should be removed.
  673. The conditions include any of 'PACKAGE_EXCLUDE, NO_RECOMMENDATIONS
  674. and BAD_RECOMMENDATIONS' has been changed.
  675. '''
  676. def _remove_old_rootfs(self):
  677. if self.inc_opkg_image_gen != "1":
  678. return True
  679. vars_list_file = self.d.expand('${T}/vars_list')
  680. old_vars_list = ""
  681. if os.path.exists(vars_list_file):
  682. old_vars_list = open(vars_list_file, 'r+').read()
  683. new_vars_list = '%s:%s:%s\n' % \
  684. ((self.d.getVar('BAD_RECOMMENDATIONS') or '').strip(),
  685. (self.d.getVar('NO_RECOMMENDATIONS') or '').strip(),
  686. (self.d.getVar('PACKAGE_EXCLUDE') or '').strip())
  687. open(vars_list_file, 'w+').write(new_vars_list)
  688. if old_vars_list != new_vars_list:
  689. return True
  690. return False
  691. def _create(self):
  692. pkgs_to_install = self.manifest.parse_initial_manifest()
  693. opkg_pre_process_cmds = self.d.getVar('OPKG_PREPROCESS_COMMANDS')
  694. opkg_post_process_cmds = self.d.getVar('OPKG_POSTPROCESS_COMMANDS')
  695. # update PM index files
  696. self.pm.write_index()
  697. execute_pre_post_process(self.d, opkg_pre_process_cmds)
  698. if self.progress_reporter:
  699. self.progress_reporter.next_stage()
  700. # Steps are a bit different in order, skip next
  701. self.progress_reporter.next_stage()
  702. self.pm.update()
  703. if self.progress_reporter:
  704. self.progress_reporter.next_stage()
  705. if self.inc_opkg_image_gen == "1":
  706. self._remove_extra_packages(pkgs_to_install)
  707. if self.progress_reporter:
  708. self.progress_reporter.next_stage()
  709. for pkg_type in self.install_order:
  710. if pkg_type in pkgs_to_install:
  711. # For multilib, we perform a sanity test before final install
  712. # If sanity test fails, it will automatically do a bb.fatal()
  713. # and the installation will stop
  714. if pkg_type == Manifest.PKG_TYPE_MULTILIB:
  715. self._multilib_test_install(pkgs_to_install[pkg_type])
  716. self.pm.install(pkgs_to_install[pkg_type],
  717. [False, True][pkg_type == Manifest.PKG_TYPE_ATTEMPT_ONLY])
  718. if self.progress_reporter:
  719. self.progress_reporter.next_stage()
  720. self.pm.install_complementary()
  721. if self.progress_reporter:
  722. self.progress_reporter.next_stage()
  723. opkg_lib_dir = self.d.getVar('OPKGLIBDIR')
  724. opkg_dir = os.path.join(opkg_lib_dir, 'opkg')
  725. self._setup_dbg_rootfs([opkg_dir])
  726. execute_pre_post_process(self.d, opkg_post_process_cmds)
  727. if self.inc_opkg_image_gen == "1":
  728. self.pm.backup_packaging_data()
  729. if self.progress_reporter:
  730. self.progress_reporter.next_stage()
  731. @staticmethod
  732. def _depends_list():
  733. return ['IPKGCONF_SDK', 'IPK_FEED_URIS', 'DEPLOY_DIR_IPK', 'IPKGCONF_TARGET', 'INC_IPK_IMAGE_GEN', 'OPKG_ARGS', 'OPKGLIBDIR', 'OPKG_PREPROCESS_COMMANDS', 'OPKG_POSTPROCESS_COMMANDS', 'OPKGLIBDIR']
  734. def _get_delayed_postinsts(self):
  735. status_file = os.path.join(self.image_rootfs,
  736. self.d.getVar('OPKGLIBDIR').strip('/'),
  737. "opkg", "status")
  738. return self._get_delayed_postinsts_common(status_file)
  739. def _save_postinsts(self):
  740. dst_postinst_dir = self.d.expand("${IMAGE_ROOTFS}${sysconfdir}/ipk-postinsts")
  741. src_postinst_dir = self.d.expand("${IMAGE_ROOTFS}${OPKGLIBDIR}/opkg/info")
  742. return self._save_postinsts_common(dst_postinst_dir, src_postinst_dir)
  743. def _log_check(self):
  744. self._log_check_warn()
  745. self._log_check_error()
  746. def _cleanup(self):
  747. self.pm.remove_lists()
  748. def get_class_for_type(imgtype):
  749. return {"rpm": RpmRootfs,
  750. "ipk": OpkgRootfs,
  751. "deb": DpkgRootfs}[imgtype]
  752. def variable_depends(d, manifest_dir=None):
  753. img_type = d.getVar('IMAGE_PKGTYPE')
  754. cls = get_class_for_type(img_type)
  755. return cls._depends_list()
  756. def create_rootfs(d, manifest_dir=None, progress_reporter=None, logcatcher=None):
  757. env_bkp = os.environ.copy()
  758. img_type = d.getVar('IMAGE_PKGTYPE')
  759. if img_type == "rpm":
  760. RpmRootfs(d, manifest_dir, progress_reporter, logcatcher).create()
  761. elif img_type == "ipk":
  762. OpkgRootfs(d, manifest_dir, progress_reporter, logcatcher).create()
  763. elif img_type == "deb":
  764. DpkgRootfs(d, manifest_dir, progress_reporter, logcatcher).create()
  765. os.environ.clear()
  766. os.environ.update(env_bkp)
  767. def image_list_installed_packages(d, rootfs_dir=None):
  768. if not rootfs_dir:
  769. rootfs_dir = d.getVar('IMAGE_ROOTFS')
  770. img_type = d.getVar('IMAGE_PKGTYPE')
  771. if img_type == "rpm":
  772. return RpmPkgsList(d, rootfs_dir).list_pkgs()
  773. elif img_type == "ipk":
  774. return OpkgPkgsList(d, rootfs_dir, d.getVar("IPKGCONF_TARGET")).list_pkgs()
  775. elif img_type == "deb":
  776. return DpkgPkgsList(d, rootfs_dir).list_pkgs()
  777. if __name__ == "__main__":
  778. """
  779. We should be able to run this as a standalone script, from outside bitbake
  780. environment.
  781. """
  782. """
  783. TBD
  784. """