rootfs.py 36 KB

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