rootfs.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. #
  2. # Copyright OpenEmbedded Contributors
  3. #
  4. # SPDX-License-Identifier: GPL-2.0-only
  5. #
  6. from abc import ABCMeta, abstractmethod
  7. from oe.utils import execute_pre_post_process
  8. from oe.package_manager import *
  9. from oe.manifest import *
  10. import oe.path
  11. import shutil
  12. import os
  13. import subprocess
  14. import re
  15. class Rootfs(object, metaclass=ABCMeta):
  16. """
  17. This is an abstract class. Do not instantiate this directly.
  18. """
  19. def __init__(self, d, progress_reporter=None, logcatcher=None):
  20. self.d = d
  21. self.pm = None
  22. self.image_rootfs = self.d.getVar('IMAGE_ROOTFS')
  23. self.deploydir = self.d.getVar('IMGDEPLOYDIR')
  24. self.progress_reporter = progress_reporter
  25. self.logcatcher = logcatcher
  26. self.install_order = Manifest.INSTALL_ORDER
  27. @abstractmethod
  28. def _create(self):
  29. pass
  30. @abstractmethod
  31. def _get_delayed_postinsts(self):
  32. pass
  33. @abstractmethod
  34. def _save_postinsts(self):
  35. pass
  36. @abstractmethod
  37. def _log_check(self):
  38. pass
  39. def _log_check_common(self, type, match):
  40. # Ignore any lines containing log_check to avoid recursion, and ignore
  41. # lines beginning with a + since sh -x may emit code which isn't
  42. # actually executed, but may contain error messages
  43. excludes = [ 'log_check', r'^\+' ]
  44. if hasattr(self, 'log_check_expected_regexes'):
  45. excludes.extend(self.log_check_expected_regexes)
  46. # Insert custom log_check excludes
  47. excludes += [x for x in (self.d.getVar("IMAGE_LOG_CHECK_EXCLUDES") or "").split(" ") if x]
  48. excludes = [re.compile(x) for x in excludes]
  49. r = re.compile(match)
  50. log_path = self.d.expand("${T}/log.do_rootfs")
  51. messages = []
  52. with open(log_path, 'r') as log:
  53. for line in log:
  54. if self.logcatcher and self.logcatcher.contains(line.rstrip()):
  55. continue
  56. for ee in excludes:
  57. m = ee.search(line)
  58. if m:
  59. break
  60. if m:
  61. continue
  62. m = r.search(line)
  63. if m:
  64. messages.append('[log_check] %s' % line)
  65. if messages:
  66. if len(messages) == 1:
  67. msg = '1 %s message' % type
  68. else:
  69. msg = '%d %s messages' % (len(messages), type)
  70. msg = '[log_check] %s: found %s in the logfile:\n%s' % \
  71. (self.d.getVar('PN'), msg, ''.join(messages))
  72. if type == 'error':
  73. bb.fatal(msg)
  74. else:
  75. bb.warn(msg)
  76. def _log_check_warn(self):
  77. self._log_check_common('warning', '^(warn|Warn|WARNING:)')
  78. def _log_check_error(self):
  79. self._log_check_common('error', self.log_check_regex)
  80. def _insert_feed_uris(self):
  81. if bb.utils.contains("IMAGE_FEATURES", "package-management",
  82. True, False, self.d):
  83. self.pm.insert_feeds_uris(self.d.getVar('PACKAGE_FEED_URIS') or "",
  84. self.d.getVar('PACKAGE_FEED_BASE_PATHS') or "",
  85. self.d.getVar('PACKAGE_FEED_ARCHS'))
  86. """
  87. The _cleanup() method should be used to clean-up stuff that we don't really
  88. want to end up on target. For example, in the case of RPM, the DB locks.
  89. The method is called, once, at the end of create() method.
  90. """
  91. @abstractmethod
  92. def _cleanup(self):
  93. pass
  94. def _setup_dbg_rootfs(self, package_paths):
  95. gen_debugfs = self.d.getVar('IMAGE_GEN_DEBUGFS') or '0'
  96. if gen_debugfs != '1':
  97. return
  98. bb.note(" Renaming the original rootfs...")
  99. try:
  100. shutil.rmtree(self.image_rootfs + '-orig')
  101. except:
  102. pass
  103. bb.utils.rename(self.image_rootfs, self.image_rootfs + '-orig')
  104. bb.note(" Creating debug rootfs...")
  105. bb.utils.mkdirhier(self.image_rootfs)
  106. bb.note(" Copying back package database...")
  107. for path in package_paths:
  108. bb.utils.mkdirhier(self.image_rootfs + os.path.dirname(path))
  109. if os.path.isdir(self.image_rootfs + '-orig' + path):
  110. shutil.copytree(self.image_rootfs + '-orig' + path, self.image_rootfs + path, symlinks=True)
  111. elif os.path.isfile(self.image_rootfs + '-orig' + path):
  112. shutil.copyfile(self.image_rootfs + '-orig' + path, self.image_rootfs + path)
  113. # Copy files located in /usr/lib/debug or /usr/src/debug
  114. for dir in ["/usr/lib/debug", "/usr/src/debug"]:
  115. src = self.image_rootfs + '-orig' + dir
  116. if os.path.exists(src):
  117. dst = self.image_rootfs + dir
  118. bb.utils.mkdirhier(os.path.dirname(dst))
  119. shutil.copytree(src, dst)
  120. # Copy files with suffix '.debug' or located in '.debug' dir.
  121. for root, dirs, files in os.walk(self.image_rootfs + '-orig'):
  122. relative_dir = root[len(self.image_rootfs + '-orig'):]
  123. for f in files:
  124. if f.endswith('.debug') or '/.debug' in relative_dir:
  125. bb.utils.mkdirhier(self.image_rootfs + relative_dir)
  126. shutil.copy(os.path.join(root, f),
  127. self.image_rootfs + relative_dir)
  128. bb.note(" Install complementary '*-dbg' packages...")
  129. self.pm.install_complementary('*-dbg')
  130. if self.d.getVar('PACKAGE_DEBUG_SPLIT_STYLE') == 'debug-with-srcpkg':
  131. bb.note(" Install complementary '*-src' packages...")
  132. self.pm.install_complementary('*-src')
  133. """
  134. Install additional debug packages. Possibility to install additional packages,
  135. which are not automatically installed as complementary package of
  136. standard one, e.g. debug package of static libraries.
  137. """
  138. extra_debug_pkgs = self.d.getVar('IMAGE_INSTALL_DEBUGFS')
  139. if extra_debug_pkgs:
  140. bb.note(" Install extra debug packages...")
  141. self.pm.install(extra_debug_pkgs.split(), True)
  142. bb.note(" Removing package database...")
  143. for path in package_paths:
  144. if os.path.isdir(self.image_rootfs + path):
  145. shutil.rmtree(self.image_rootfs + path)
  146. elif os.path.isfile(self.image_rootfs + path):
  147. os.remove(self.image_rootfs + path)
  148. bb.note(" Rename debug rootfs...")
  149. try:
  150. shutil.rmtree(self.image_rootfs + '-dbg')
  151. except:
  152. pass
  153. bb.utils.rename(self.image_rootfs, self.image_rootfs + '-dbg')
  154. bb.note(" Restoring original rootfs...")
  155. bb.utils.rename(self.image_rootfs + '-orig', self.image_rootfs)
  156. def _exec_shell_cmd(self, cmd):
  157. try:
  158. subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  159. except subprocess.CalledProcessError as e:
  160. return("Command '%s' returned %d:\n%s" % (e.cmd, e.returncode, e.output))
  161. return None
  162. def create(self):
  163. bb.note("###### Generate rootfs #######")
  164. pre_process_cmds = self.d.getVar("ROOTFS_PREPROCESS_COMMAND")
  165. post_process_cmds = self.d.getVar("ROOTFS_POSTPROCESS_COMMAND")
  166. rootfs_post_install_cmds = self.d.getVar('ROOTFS_POSTINSTALL_COMMAND')
  167. def make_last(command, commands):
  168. commands = commands.split()
  169. if command in commands:
  170. commands.remove(command)
  171. commands.append(command)
  172. return " ".join(commands)
  173. # We want this to run as late as possible, in particular after
  174. # systemd_sysusers_create and set_user_group. Using :append is not enough
  175. post_process_cmds = make_last("tidy_shadowutils_files", post_process_cmds)
  176. post_process_cmds = make_last("rootfs_reproducible", post_process_cmds)
  177. execute_pre_post_process(self.d, pre_process_cmds)
  178. if self.progress_reporter:
  179. self.progress_reporter.next_stage()
  180. # call the package manager dependent create method
  181. self._create()
  182. sysconfdir = self.image_rootfs + self.d.getVar('sysconfdir')
  183. bb.utils.mkdirhier(sysconfdir)
  184. with open(sysconfdir + "/version", "w+") as ver:
  185. ver.write(self.d.getVar('BUILDNAME') + "\n")
  186. execute_pre_post_process(self.d, rootfs_post_install_cmds)
  187. self.pm.run_intercepts()
  188. execute_pre_post_process(self.d, post_process_cmds)
  189. if self.progress_reporter:
  190. self.progress_reporter.next_stage()
  191. if bb.utils.contains("IMAGE_FEATURES", "read-only-rootfs",
  192. True, False, self.d) and \
  193. not bb.utils.contains("IMAGE_FEATURES",
  194. "read-only-rootfs-delayed-postinsts",
  195. True, False, self.d):
  196. delayed_postinsts = self._get_delayed_postinsts()
  197. if delayed_postinsts is not None:
  198. bb.fatal("The following packages could not be configured "
  199. "offline and rootfs is read-only: %s" %
  200. delayed_postinsts)
  201. if self.d.getVar('USE_DEVFS') != "1":
  202. self._create_devfs()
  203. self._uninstall_unneeded()
  204. if self.progress_reporter:
  205. self.progress_reporter.next_stage()
  206. self._insert_feed_uris()
  207. self._run_ldconfig()
  208. if self.d.getVar('USE_DEPMOD') != "0":
  209. self._generate_kernel_module_deps()
  210. self._cleanup()
  211. self._log_check()
  212. if self.progress_reporter:
  213. self.progress_reporter.next_stage()
  214. def _uninstall_unneeded(self):
  215. # Remove the run-postinsts package if no delayed postinsts are found
  216. delayed_postinsts = self._get_delayed_postinsts()
  217. if delayed_postinsts is None:
  218. if os.path.exists(self.d.expand("${IMAGE_ROOTFS}${sysconfdir}/init.d/run-postinsts")) or os.path.exists(self.d.expand("${IMAGE_ROOTFS}${systemd_system_unitdir}/run-postinsts.service")):
  219. self.pm.remove(["run-postinsts"])
  220. image_rorfs = bb.utils.contains("IMAGE_FEATURES", "read-only-rootfs",
  221. True, False, self.d) and \
  222. not bb.utils.contains("IMAGE_FEATURES",
  223. "read-only-rootfs-delayed-postinsts",
  224. True, False, self.d)
  225. image_rorfs_force = self.d.getVar('FORCE_RO_REMOVE')
  226. if image_rorfs or image_rorfs_force == "1":
  227. # Remove components that we don't need if it's a read-only rootfs
  228. unneeded_pkgs = self.d.getVar("ROOTFS_RO_UNNEEDED").split()
  229. pkgs_installed = image_list_installed_packages(self.d)
  230. # Make sure update-alternatives is removed last. This is
  231. # because its database has to available while uninstalling
  232. # other packages, allowing alternative symlinks of packages
  233. # to be uninstalled or to be managed correctly otherwise.
  234. provider = self.d.getVar("VIRTUAL-RUNTIME_update-alternatives")
  235. pkgs_to_remove = sorted([pkg for pkg in pkgs_installed if pkg in unneeded_pkgs], key=lambda x: x == provider)
  236. # update-alternatives provider is removed in its own remove()
  237. # call because all package managers do not guarantee the packages
  238. # are removed in the order they given in the list (which is
  239. # passed to the command line). The sorting done earlier is
  240. # utilized to implement the 2-stage removal.
  241. if len(pkgs_to_remove) > 1:
  242. self.pm.remove(pkgs_to_remove[:-1], False)
  243. if len(pkgs_to_remove) > 0:
  244. self.pm.remove([pkgs_to_remove[-1]], False)
  245. if delayed_postinsts:
  246. self._save_postinsts()
  247. if image_rorfs:
  248. bb.warn("There are post install scripts "
  249. "in a read-only rootfs")
  250. post_uninstall_cmds = self.d.getVar("ROOTFS_POSTUNINSTALL_COMMAND")
  251. execute_pre_post_process(self.d, post_uninstall_cmds)
  252. runtime_pkgmanage = bb.utils.contains("IMAGE_FEATURES", "package-management",
  253. True, False, self.d)
  254. if not runtime_pkgmanage:
  255. # Remove the package manager data files
  256. self.pm.remove_packaging_data()
  257. def _run_ldconfig(self):
  258. if self.d.getVar('LDCONFIGDEPEND'):
  259. bb.note("Executing: ldconfig -r " + self.image_rootfs + " -c new -v -X")
  260. self._exec_shell_cmd(['ldconfig', '-r', self.image_rootfs, '-c',
  261. 'new', '-v', '-X'])
  262. image_rorfs = bb.utils.contains("IMAGE_FEATURES", "read-only-rootfs",
  263. True, False, self.d)
  264. ldconfig_in_features = bb.utils.contains("DISTRO_FEATURES", "ldconfig",
  265. True, False, self.d)
  266. if image_rorfs or not ldconfig_in_features:
  267. ldconfig_cache_dir = os.path.join(self.image_rootfs, "var/cache/ldconfig")
  268. if os.path.exists(ldconfig_cache_dir):
  269. bb.note("Removing ldconfig auxiliary cache...")
  270. shutil.rmtree(ldconfig_cache_dir)
  271. def _check_for_kernel_modules(self, modules_dir):
  272. for root, dirs, files in os.walk(modules_dir, topdown=True):
  273. for name in files:
  274. found_ko = name.endswith((".ko", ".ko.gz", ".ko.xz", ".ko.zst"))
  275. if found_ko:
  276. return found_ko
  277. return False
  278. def _generate_kernel_module_deps(self):
  279. modules_dir = os.path.join(self.image_rootfs, 'lib', 'modules')
  280. # if we don't have any modules don't bother to do the depmod
  281. if not self._check_for_kernel_modules(modules_dir):
  282. bb.note("No Kernel Modules found, not running depmod")
  283. return
  284. pkgdatadir = self.d.getVar('PKGDATA_DIR')
  285. # PKGDATA_DIR can include multiple kernels so we run depmod for each
  286. # one of them.
  287. for direntry in os.listdir(pkgdatadir):
  288. match = re.match('(.*)-depmod', direntry)
  289. if not match:
  290. continue
  291. kernel_package_name = match.group(1)
  292. kernel_abi_ver_file = oe.path.join(pkgdatadir, direntry, kernel_package_name + '-abiversion')
  293. if not os.path.exists(kernel_abi_ver_file):
  294. bb.fatal("No kernel-abiversion file found (%s), cannot run depmod, aborting" % kernel_abi_ver_file)
  295. with open(kernel_abi_ver_file) as f:
  296. kernel_ver = f.read().strip(' \n')
  297. versioned_modules_dir = os.path.join(self.image_rootfs, modules_dir, kernel_ver)
  298. if os.path.exists(versioned_modules_dir):
  299. bb.note("Running depmodwrapper for %s ..." % versioned_modules_dir)
  300. if self._exec_shell_cmd(['depmodwrapper', '-a', '-b', self.image_rootfs, kernel_ver, kernel_package_name]):
  301. bb.fatal("Kernel modules dependency generation failed")
  302. else:
  303. bb.note("Not running depmodwrapper for %s since directory does not exist" % versioned_modules_dir)
  304. """
  305. Create devfs:
  306. * IMAGE_DEVICE_TABLE is the old name to an absolute path to a device table file
  307. * IMAGE_DEVICE_TABLES is a new name for a file, or list of files, seached
  308. for in the BBPATH
  309. If neither are specified then the default name of files/device_table-minimal.txt
  310. is searched for in the BBPATH (same as the old version.)
  311. """
  312. def _create_devfs(self):
  313. devtable_list = []
  314. devtable = self.d.getVar('IMAGE_DEVICE_TABLE')
  315. if devtable is not None:
  316. devtable_list.append(devtable)
  317. else:
  318. devtables = self.d.getVar('IMAGE_DEVICE_TABLES')
  319. if devtables is None:
  320. devtables = 'files/device_table-minimal.txt'
  321. for devtable in devtables.split():
  322. devtable_list.append("%s" % bb.utils.which(self.d.getVar('BBPATH'), devtable))
  323. for devtable in devtable_list:
  324. self._exec_shell_cmd(["makedevs", "-r",
  325. self.image_rootfs, "-D", devtable])
  326. def get_class_for_type(imgtype):
  327. import importlib
  328. mod = importlib.import_module('oe.package_manager.' + imgtype + '.rootfs')
  329. return mod.PkgRootfs
  330. def variable_depends(d, manifest_dir=None):
  331. img_type = d.getVar('IMAGE_PKGTYPE')
  332. cls = get_class_for_type(img_type)
  333. return cls._depends_list()
  334. def create_rootfs(d, manifest_dir=None, progress_reporter=None, logcatcher=None):
  335. env_bkp = os.environ.copy()
  336. img_type = d.getVar('IMAGE_PKGTYPE')
  337. cls = get_class_for_type(img_type)
  338. cls(d, manifest_dir, progress_reporter, logcatcher).create()
  339. os.environ.clear()
  340. os.environ.update(env_bkp)
  341. def image_list_installed_packages(d, rootfs_dir=None):
  342. # Theres no rootfs for baremetal images
  343. if bb.data.inherits_class('baremetal-image', d):
  344. return ""
  345. if not rootfs_dir:
  346. rootfs_dir = d.getVar('IMAGE_ROOTFS')
  347. img_type = d.getVar('IMAGE_PKGTYPE')
  348. import importlib
  349. cls = importlib.import_module('oe.package_manager.' + img_type)
  350. return cls.PMPkgsList(d, rootfs_dir).list_pkgs()