package_manager.py 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849
  1. #
  2. # SPDX-License-Identifier: GPL-2.0-only
  3. #
  4. from abc import ABCMeta, abstractmethod
  5. import os
  6. import glob
  7. import subprocess
  8. import shutil
  9. import re
  10. import collections
  11. import bb
  12. import tempfile
  13. import oe.utils
  14. import oe.path
  15. import string
  16. from oe.gpg_sign import get_signer
  17. import hashlib
  18. import fnmatch
  19. # this can be used by all PM backends to create the index files in parallel
  20. def create_index(arg):
  21. index_cmd = arg
  22. bb.note("Executing '%s' ..." % index_cmd)
  23. result = subprocess.check_output(index_cmd, stderr=subprocess.STDOUT, shell=True).decode("utf-8")
  24. if result:
  25. bb.note(result)
  26. def opkg_query(cmd_output):
  27. """
  28. This method parse the output from the package managerand return
  29. a dictionary with the information of the packages. This is used
  30. when the packages are in deb or ipk format.
  31. """
  32. verregex = re.compile(r' \([=<>]* [^ )]*\)')
  33. output = dict()
  34. pkg = ""
  35. arch = ""
  36. ver = ""
  37. filename = ""
  38. dep = []
  39. pkgarch = ""
  40. for line in cmd_output.splitlines():
  41. line = line.rstrip()
  42. if ':' in line:
  43. if line.startswith("Package: "):
  44. pkg = line.split(": ")[1]
  45. elif line.startswith("Architecture: "):
  46. arch = line.split(": ")[1]
  47. elif line.startswith("Version: "):
  48. ver = line.split(": ")[1]
  49. elif line.startswith("File: ") or line.startswith("Filename:"):
  50. filename = line.split(": ")[1]
  51. if "/" in filename:
  52. filename = os.path.basename(filename)
  53. elif line.startswith("Depends: "):
  54. depends = verregex.sub('', line.split(": ")[1])
  55. for depend in depends.split(", "):
  56. dep.append(depend)
  57. elif line.startswith("Recommends: "):
  58. recommends = verregex.sub('', line.split(": ")[1])
  59. for recommend in recommends.split(", "):
  60. dep.append("%s [REC]" % recommend)
  61. elif line.startswith("PackageArch: "):
  62. pkgarch = line.split(": ")[1]
  63. # When there is a blank line save the package information
  64. elif not line:
  65. # IPK doesn't include the filename
  66. if not filename:
  67. filename = "%s_%s_%s.ipk" % (pkg, ver, arch)
  68. if pkg:
  69. output[pkg] = {"arch":arch, "ver":ver,
  70. "filename":filename, "deps": dep, "pkgarch":pkgarch }
  71. pkg = ""
  72. arch = ""
  73. ver = ""
  74. filename = ""
  75. dep = []
  76. pkgarch = ""
  77. if pkg:
  78. if not filename:
  79. filename = "%s_%s_%s.ipk" % (pkg, ver, arch)
  80. output[pkg] = {"arch":arch, "ver":ver,
  81. "filename":filename, "deps": dep }
  82. return output
  83. def failed_postinsts_abort(pkgs, log_path):
  84. bb.fatal("""Postinstall scriptlets of %s have failed. If the intention is to defer them to first boot,
  85. then please place them into pkg_postinst_ontarget_${PN} ().
  86. Deferring to first boot via 'exit 1' is no longer supported.
  87. Details of the failure are in %s.""" %(pkgs, log_path))
  88. def generate_locale_archive(d, rootfs, target_arch, localedir):
  89. # Pretty sure we don't need this for locale archive generation but
  90. # keeping it to be safe...
  91. locale_arch_options = { \
  92. "arc": ["--uint32-align=4", "--little-endian"],
  93. "arceb": ["--uint32-align=4", "--big-endian"],
  94. "arm": ["--uint32-align=4", "--little-endian"],
  95. "armeb": ["--uint32-align=4", "--big-endian"],
  96. "aarch64": ["--uint32-align=4", "--little-endian"],
  97. "aarch64_be": ["--uint32-align=4", "--big-endian"],
  98. "sh4": ["--uint32-align=4", "--big-endian"],
  99. "powerpc": ["--uint32-align=4", "--big-endian"],
  100. "powerpc64": ["--uint32-align=4", "--big-endian"],
  101. "mips": ["--uint32-align=4", "--big-endian"],
  102. "mipsisa32r6": ["--uint32-align=4", "--big-endian"],
  103. "mips64": ["--uint32-align=4", "--big-endian"],
  104. "mipsisa64r6": ["--uint32-align=4", "--big-endian"],
  105. "mipsel": ["--uint32-align=4", "--little-endian"],
  106. "mipsisa32r6el": ["--uint32-align=4", "--little-endian"],
  107. "mips64el": ["--uint32-align=4", "--little-endian"],
  108. "mipsisa64r6el": ["--uint32-align=4", "--little-endian"],
  109. "riscv64": ["--uint32-align=4", "--little-endian"],
  110. "riscv32": ["--uint32-align=4", "--little-endian"],
  111. "i586": ["--uint32-align=4", "--little-endian"],
  112. "i686": ["--uint32-align=4", "--little-endian"],
  113. "x86_64": ["--uint32-align=4", "--little-endian"]
  114. }
  115. if target_arch in locale_arch_options:
  116. arch_options = locale_arch_options[target_arch]
  117. else:
  118. bb.error("locale_arch_options not found for target_arch=" + target_arch)
  119. bb.fatal("unknown arch:" + target_arch + " for locale_arch_options")
  120. # Need to set this so cross-localedef knows where the archive is
  121. env = dict(os.environ)
  122. env["LOCALEARCHIVE"] = oe.path.join(localedir, "locale-archive")
  123. for name in os.listdir(localedir):
  124. path = os.path.join(localedir, name)
  125. if os.path.isdir(path):
  126. cmd = ["cross-localedef", "--verbose"]
  127. cmd += arch_options
  128. cmd += ["--add-to-archive", path]
  129. subprocess.check_output(cmd, env=env, stderr=subprocess.STDOUT)
  130. class Indexer(object, metaclass=ABCMeta):
  131. def __init__(self, d, deploy_dir):
  132. self.d = d
  133. self.deploy_dir = deploy_dir
  134. @abstractmethod
  135. def write_index(self):
  136. pass
  137. class RpmIndexer(Indexer):
  138. def write_index(self):
  139. self.do_write_index(self.deploy_dir)
  140. def do_write_index(self, deploy_dir):
  141. if self.d.getVar('PACKAGE_FEED_SIGN') == '1':
  142. signer = get_signer(self.d, self.d.getVar('PACKAGE_FEED_GPG_BACKEND'))
  143. else:
  144. signer = None
  145. createrepo_c = bb.utils.which(os.environ['PATH'], "createrepo_c")
  146. result = create_index("%s --update -q %s" % (createrepo_c, deploy_dir))
  147. if result:
  148. bb.fatal(result)
  149. # Sign repomd
  150. if signer:
  151. sig_type = self.d.getVar('PACKAGE_FEED_GPG_SIGNATURE_TYPE')
  152. is_ascii_sig = (sig_type.upper() != "BIN")
  153. signer.detach_sign(os.path.join(deploy_dir, 'repodata', 'repomd.xml'),
  154. self.d.getVar('PACKAGE_FEED_GPG_NAME'),
  155. self.d.getVar('PACKAGE_FEED_GPG_PASSPHRASE_FILE'),
  156. armor=is_ascii_sig)
  157. class RpmSubdirIndexer(RpmIndexer):
  158. def write_index(self):
  159. bb.note("Generating package index for %s" %(self.deploy_dir))
  160. self.do_write_index(self.deploy_dir)
  161. for entry in os.walk(self.deploy_dir):
  162. if os.path.samefile(self.deploy_dir, entry[0]):
  163. for dir in entry[1]:
  164. if dir != 'repodata':
  165. dir_path = oe.path.join(self.deploy_dir, dir)
  166. bb.note("Generating package index for %s" %(dir_path))
  167. self.do_write_index(dir_path)
  168. class OpkgIndexer(Indexer):
  169. def write_index(self):
  170. arch_vars = ["ALL_MULTILIB_PACKAGE_ARCHS",
  171. "SDK_PACKAGE_ARCHS",
  172. ]
  173. opkg_index_cmd = bb.utils.which(os.getenv('PATH'), "opkg-make-index")
  174. if self.d.getVar('PACKAGE_FEED_SIGN') == '1':
  175. signer = get_signer(self.d, self.d.getVar('PACKAGE_FEED_GPG_BACKEND'))
  176. else:
  177. signer = None
  178. if not os.path.exists(os.path.join(self.deploy_dir, "Packages")):
  179. open(os.path.join(self.deploy_dir, "Packages"), "w").close()
  180. index_cmds = set()
  181. index_sign_files = set()
  182. for arch_var in arch_vars:
  183. archs = self.d.getVar(arch_var)
  184. if archs is None:
  185. continue
  186. for arch in archs.split():
  187. pkgs_dir = os.path.join(self.deploy_dir, arch)
  188. pkgs_file = os.path.join(pkgs_dir, "Packages")
  189. if not os.path.isdir(pkgs_dir):
  190. continue
  191. if not os.path.exists(pkgs_file):
  192. open(pkgs_file, "w").close()
  193. index_cmds.add('%s -r %s -p %s -m %s' %
  194. (opkg_index_cmd, pkgs_file, pkgs_file, pkgs_dir))
  195. index_sign_files.add(pkgs_file)
  196. if len(index_cmds) == 0:
  197. bb.note("There are no packages in %s!" % self.deploy_dir)
  198. return
  199. oe.utils.multiprocess_launch(create_index, index_cmds, self.d)
  200. if signer:
  201. feed_sig_type = self.d.getVar('PACKAGE_FEED_GPG_SIGNATURE_TYPE')
  202. is_ascii_sig = (feed_sig_type.upper() != "BIN")
  203. for f in index_sign_files:
  204. signer.detach_sign(f,
  205. self.d.getVar('PACKAGE_FEED_GPG_NAME'),
  206. self.d.getVar('PACKAGE_FEED_GPG_PASSPHRASE_FILE'),
  207. armor=is_ascii_sig)
  208. class DpkgIndexer(Indexer):
  209. def _create_configs(self):
  210. bb.utils.mkdirhier(self.apt_conf_dir)
  211. bb.utils.mkdirhier(os.path.join(self.apt_conf_dir, "lists", "partial"))
  212. bb.utils.mkdirhier(os.path.join(self.apt_conf_dir, "apt.conf.d"))
  213. bb.utils.mkdirhier(os.path.join(self.apt_conf_dir, "preferences.d"))
  214. with open(os.path.join(self.apt_conf_dir, "preferences"),
  215. "w") as prefs_file:
  216. pass
  217. with open(os.path.join(self.apt_conf_dir, "sources.list"),
  218. "w+") as sources_file:
  219. pass
  220. with open(self.apt_conf_file, "w") as apt_conf:
  221. with open(os.path.join(self.d.expand("${STAGING_ETCDIR_NATIVE}"),
  222. "apt", "apt.conf.sample")) as apt_conf_sample:
  223. for line in apt_conf_sample.read().split("\n"):
  224. line = re.sub(r"#ROOTFS#", "/dev/null", line)
  225. line = re.sub(r"#APTCONF#", self.apt_conf_dir, line)
  226. apt_conf.write(line + "\n")
  227. def write_index(self):
  228. self.apt_conf_dir = os.path.join(self.d.expand("${APTCONF_TARGET}"),
  229. "apt-ftparchive")
  230. self.apt_conf_file = os.path.join(self.apt_conf_dir, "apt.conf")
  231. self._create_configs()
  232. os.environ['APT_CONFIG'] = self.apt_conf_file
  233. pkg_archs = self.d.getVar('PACKAGE_ARCHS')
  234. if pkg_archs is not None:
  235. arch_list = pkg_archs.split()
  236. sdk_pkg_archs = self.d.getVar('SDK_PACKAGE_ARCHS')
  237. if sdk_pkg_archs is not None:
  238. for a in sdk_pkg_archs.split():
  239. if a not in pkg_archs:
  240. arch_list.append(a)
  241. all_mlb_pkg_arch_list = (self.d.getVar('ALL_MULTILIB_PACKAGE_ARCHS') or "").split()
  242. arch_list.extend(arch for arch in all_mlb_pkg_arch_list if arch not in arch_list)
  243. apt_ftparchive = bb.utils.which(os.getenv('PATH'), "apt-ftparchive")
  244. gzip = bb.utils.which(os.getenv('PATH'), "gzip")
  245. index_cmds = []
  246. deb_dirs_found = False
  247. for arch in arch_list:
  248. arch_dir = os.path.join(self.deploy_dir, arch)
  249. if not os.path.isdir(arch_dir):
  250. continue
  251. cmd = "cd %s; PSEUDO_UNLOAD=1 %s packages . > Packages;" % (arch_dir, apt_ftparchive)
  252. cmd += "%s -fcn Packages > Packages.gz;" % gzip
  253. with open(os.path.join(arch_dir, "Release"), "w+") as release:
  254. release.write("Label: %s\n" % arch)
  255. cmd += "PSEUDO_UNLOAD=1 %s release . >> Release" % apt_ftparchive
  256. index_cmds.append(cmd)
  257. deb_dirs_found = True
  258. if not deb_dirs_found:
  259. bb.note("There are no packages in %s" % self.deploy_dir)
  260. return
  261. oe.utils.multiprocess_launch(create_index, index_cmds, self.d)
  262. if self.d.getVar('PACKAGE_FEED_SIGN') == '1':
  263. raise NotImplementedError('Package feed signing not implementd for dpkg')
  264. class PkgsList(object, metaclass=ABCMeta):
  265. def __init__(self, d, rootfs_dir):
  266. self.d = d
  267. self.rootfs_dir = rootfs_dir
  268. @abstractmethod
  269. def list_pkgs(self):
  270. pass
  271. class RpmPkgsList(PkgsList):
  272. def list_pkgs(self):
  273. return RpmPM(self.d, self.rootfs_dir, self.d.getVar('TARGET_VENDOR'), needfeed=False).list_installed()
  274. class OpkgPkgsList(PkgsList):
  275. def __init__(self, d, rootfs_dir, config_file):
  276. super(OpkgPkgsList, self).__init__(d, rootfs_dir)
  277. self.opkg_cmd = bb.utils.which(os.getenv('PATH'), "opkg")
  278. self.opkg_args = "-f %s -o %s " % (config_file, rootfs_dir)
  279. self.opkg_args += self.d.getVar("OPKG_ARGS")
  280. def list_pkgs(self, format=None):
  281. cmd = "%s %s status" % (self.opkg_cmd, self.opkg_args)
  282. # opkg returns success even when it printed some
  283. # "Collected errors:" report to stderr. Mixing stderr into
  284. # stdout then leads to random failures later on when
  285. # parsing the output. To avoid this we need to collect both
  286. # output streams separately and check for empty stderr.
  287. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  288. cmd_output, cmd_stderr = p.communicate()
  289. cmd_output = cmd_output.decode("utf-8")
  290. cmd_stderr = cmd_stderr.decode("utf-8")
  291. if p.returncode or cmd_stderr:
  292. bb.fatal("Cannot get the installed packages list. Command '%s' "
  293. "returned %d and stderr:\n%s" % (cmd, p.returncode, cmd_stderr))
  294. return opkg_query(cmd_output)
  295. class DpkgPkgsList(PkgsList):
  296. def list_pkgs(self):
  297. cmd = [bb.utils.which(os.getenv('PATH'), "dpkg-query"),
  298. "--admindir=%s/var/lib/dpkg" % self.rootfs_dir,
  299. "-W"]
  300. cmd.append("-f=Package: ${Package}\nArchitecture: ${PackageArch}\nVersion: ${Version}\nFile: ${Package}_${Version}_${Architecture}.deb\nDepends: ${Depends}\nRecommends: ${Recommends}\n\n")
  301. try:
  302. cmd_output = subprocess.check_output(cmd, stderr=subprocess.STDOUT).strip().decode("utf-8")
  303. except subprocess.CalledProcessError as e:
  304. bb.fatal("Cannot get the installed packages list. Command '%s' "
  305. "returned %d:\n%s" % (' '.join(cmd), e.returncode, e.output.decode("utf-8")))
  306. return opkg_query(cmd_output)
  307. class PackageManager(object, metaclass=ABCMeta):
  308. """
  309. This is an abstract class. Do not instantiate this directly.
  310. """
  311. def __init__(self, d, target_rootfs):
  312. self.d = d
  313. self.target_rootfs = target_rootfs
  314. self.deploy_dir = None
  315. self.deploy_lock = None
  316. self._initialize_intercepts()
  317. def _initialize_intercepts(self):
  318. bb.note("Initializing intercept dir for %s" % self.target_rootfs)
  319. # As there might be more than one instance of PackageManager operating at the same time
  320. # we need to isolate the intercept_scripts directories from each other,
  321. # hence the ugly hash digest in dir name.
  322. self.intercepts_dir = os.path.join(self.d.getVar('WORKDIR'), "intercept_scripts-%s" %
  323. (hashlib.sha256(self.target_rootfs.encode()).hexdigest()))
  324. postinst_intercepts = (self.d.getVar("POSTINST_INTERCEPTS") or "").split()
  325. if not postinst_intercepts:
  326. postinst_intercepts_path = self.d.getVar("POSTINST_INTERCEPTS_PATH")
  327. if not postinst_intercepts_path:
  328. postinst_intercepts_path = self.d.getVar("POSTINST_INTERCEPTS_DIR") or self.d.expand("${COREBASE}/scripts/postinst-intercepts")
  329. postinst_intercepts = oe.path.which_wild('*', postinst_intercepts_path)
  330. bb.debug(1, 'Collected intercepts:\n%s' % ''.join(' %s\n' % i for i in postinst_intercepts))
  331. bb.utils.remove(self.intercepts_dir, True)
  332. bb.utils.mkdirhier(self.intercepts_dir)
  333. for intercept in postinst_intercepts:
  334. bb.utils.copyfile(intercept, os.path.join(self.intercepts_dir, os.path.basename(intercept)))
  335. @abstractmethod
  336. def _handle_intercept_failure(self, failed_script):
  337. pass
  338. def _postpone_to_first_boot(self, postinst_intercept_hook):
  339. with open(postinst_intercept_hook) as intercept:
  340. registered_pkgs = None
  341. for line in intercept.read().split("\n"):
  342. m = re.match(r"^##PKGS:(.*)", line)
  343. if m is not None:
  344. registered_pkgs = m.group(1).strip()
  345. break
  346. if registered_pkgs is not None:
  347. bb.note("If an image is being built, the postinstalls for the following packages "
  348. "will be postponed for first boot: %s" %
  349. registered_pkgs)
  350. # call the backend dependent handler
  351. self._handle_intercept_failure(registered_pkgs)
  352. def run_intercepts(self, populate_sdk=None):
  353. intercepts_dir = self.intercepts_dir
  354. bb.note("Running intercept scripts:")
  355. os.environ['D'] = self.target_rootfs
  356. os.environ['STAGING_DIR_NATIVE'] = self.d.getVar('STAGING_DIR_NATIVE')
  357. for script in os.listdir(intercepts_dir):
  358. script_full = os.path.join(intercepts_dir, script)
  359. if script == "postinst_intercept" or not os.access(script_full, os.X_OK):
  360. continue
  361. # we do not want to run any multilib variant of this
  362. if script.startswith("delay_to_first_boot"):
  363. self._postpone_to_first_boot(script_full)
  364. continue
  365. if populate_sdk == 'host' and self.d.getVar('SDK_OS') == 'mingw32':
  366. bb.note("The postinstall intercept hook '%s' could not be executed due to missing wine support, details in %s/log.do_%s"
  367. % (script, self.d.getVar('T'), self.d.getVar('BB_CURRENTTASK')))
  368. continue
  369. bb.note("> Executing %s intercept ..." % script)
  370. try:
  371. output = subprocess.check_output(script_full, stderr=subprocess.STDOUT)
  372. if output: bb.note(output.decode("utf-8"))
  373. except subprocess.CalledProcessError as e:
  374. bb.note("Exit code %d. Output:\n%s" % (e.returncode, e.output.decode("utf-8")))
  375. if populate_sdk == 'host':
  376. bb.fatal("The postinstall intercept hook '%s' failed, details in %s/log.do_%s" % (script, self.d.getVar('T'), self.d.getVar('BB_CURRENTTASK')))
  377. elif populate_sdk == 'target':
  378. if "qemuwrapper: qemu usermode is not supported" in e.output.decode("utf-8"):
  379. bb.note("The postinstall intercept hook '%s' could not be executed due to missing qemu usermode support, details in %s/log.do_%s"
  380. % (script, self.d.getVar('T'), self.d.getVar('BB_CURRENTTASK')))
  381. else:
  382. bb.fatal("The postinstall intercept hook '%s' failed, details in %s/log.do_%s" % (script, self.d.getVar('T'), self.d.getVar('BB_CURRENTTASK')))
  383. else:
  384. if "qemuwrapper: qemu usermode is not supported" in e.output.decode("utf-8"):
  385. bb.note("The postinstall intercept hook '%s' could not be executed due to missing qemu usermode support, details in %s/log.do_%s"
  386. % (script, self.d.getVar('T'), self.d.getVar('BB_CURRENTTASK')))
  387. self._postpone_to_first_boot(script_full)
  388. else:
  389. bb.fatal("The postinstall intercept hook '%s' failed, details in %s/log.do_%s" % (script, self.d.getVar('T'), self.d.getVar('BB_CURRENTTASK')))
  390. @abstractmethod
  391. def update(self):
  392. """
  393. Update the package manager package database.
  394. """
  395. pass
  396. @abstractmethod
  397. def install(self, pkgs, attempt_only=False):
  398. """
  399. Install a list of packages. 'pkgs' is a list object. If 'attempt_only' is
  400. True, installation failures are ignored.
  401. """
  402. pass
  403. @abstractmethod
  404. def remove(self, pkgs, with_dependencies=True):
  405. """
  406. Remove a list of packages. 'pkgs' is a list object. If 'with_dependencies'
  407. is False, then any dependencies are left in place.
  408. """
  409. pass
  410. @abstractmethod
  411. def write_index(self):
  412. """
  413. This function creates the index files
  414. """
  415. pass
  416. @abstractmethod
  417. def remove_packaging_data(self):
  418. pass
  419. @abstractmethod
  420. def list_installed(self):
  421. pass
  422. @abstractmethod
  423. def extract(self, pkg):
  424. """
  425. Returns the path to a tmpdir where resides the contents of a package.
  426. Deleting the tmpdir is responsability of the caller.
  427. """
  428. pass
  429. @abstractmethod
  430. def insert_feeds_uris(self, feed_uris, feed_base_paths, feed_archs):
  431. """
  432. Add remote package feeds into repository manager configuration. The parameters
  433. for the feeds are set by feed_uris, feed_base_paths and feed_archs.
  434. See http://www.yoctoproject.org/docs/current/ref-manual/ref-manual.html#var-PACKAGE_FEED_URIS
  435. for their description.
  436. """
  437. pass
  438. def install_glob(self, globs, sdk=False):
  439. """
  440. Install all packages that match a glob.
  441. """
  442. # TODO don't have sdk here but have a property on the superclass
  443. # (and respect in install_complementary)
  444. if sdk:
  445. pkgdatadir = self.d.expand("${TMPDIR}/pkgdata/${SDK_SYS}")
  446. else:
  447. pkgdatadir = self.d.getVar("PKGDATA_DIR")
  448. try:
  449. bb.note("Installing globbed packages...")
  450. cmd = ["oe-pkgdata-util", "-p", pkgdatadir, "list-pkgs", globs]
  451. pkgs = subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode("utf-8")
  452. self.install(pkgs.split(), attempt_only=True)
  453. except subprocess.CalledProcessError as e:
  454. # Return code 1 means no packages matched
  455. if e.returncode != 1:
  456. bb.fatal("Could not compute globbed packages list. Command "
  457. "'%s' returned %d:\n%s" %
  458. (' '.join(cmd), e.returncode, e.output.decode("utf-8")))
  459. def install_complementary(self, globs=None):
  460. """
  461. Install complementary packages based upon the list of currently installed
  462. packages e.g. locales, *-dev, *-dbg, etc. This will only attempt to install
  463. these packages, if they don't exist then no error will occur. Note: every
  464. backend needs to call this function explicitly after the normal package
  465. installation
  466. """
  467. if globs is None:
  468. globs = self.d.getVar('IMAGE_INSTALL_COMPLEMENTARY')
  469. split_linguas = set()
  470. for translation in self.d.getVar('IMAGE_LINGUAS').split():
  471. split_linguas.add(translation)
  472. split_linguas.add(translation.split('-')[0])
  473. split_linguas = sorted(split_linguas)
  474. for lang in split_linguas:
  475. globs += " *-locale-%s" % lang
  476. if globs is None:
  477. return
  478. # we need to write the list of installed packages to a file because the
  479. # oe-pkgdata-util reads it from a file
  480. with tempfile.NamedTemporaryFile(mode="w+", prefix="installed-pkgs") as installed_pkgs:
  481. pkgs = self.list_installed()
  482. output = oe.utils.format_pkg_list(pkgs, "arch")
  483. installed_pkgs.write(output)
  484. installed_pkgs.flush()
  485. cmd = ["oe-pkgdata-util",
  486. "-p", self.d.getVar('PKGDATA_DIR'), "glob", installed_pkgs.name,
  487. globs]
  488. exclude = self.d.getVar('PACKAGE_EXCLUDE_COMPLEMENTARY')
  489. if exclude:
  490. cmd.extend(['--exclude=' + '|'.join(exclude.split())])
  491. try:
  492. bb.note("Installing complementary packages ...")
  493. bb.note('Running %s' % cmd)
  494. complementary_pkgs = subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode("utf-8")
  495. self.install(complementary_pkgs.split(), attempt_only=True)
  496. except subprocess.CalledProcessError as e:
  497. bb.fatal("Could not compute complementary packages list. Command "
  498. "'%s' returned %d:\n%s" %
  499. (' '.join(cmd), e.returncode, e.output.decode("utf-8")))
  500. target_arch = self.d.getVar('TARGET_ARCH')
  501. localedir = oe.path.join(self.target_rootfs, self.d.getVar("libdir"), "locale")
  502. if os.path.exists(localedir) and os.listdir(localedir):
  503. generate_locale_archive(self.d, self.target_rootfs, target_arch, localedir)
  504. # And now delete the binary locales
  505. self.remove(fnmatch.filter(self.list_installed(), "glibc-binary-localedata-*"), False)
  506. def deploy_dir_lock(self):
  507. if self.deploy_dir is None:
  508. raise RuntimeError("deploy_dir is not set!")
  509. lock_file_name = os.path.join(self.deploy_dir, "deploy.lock")
  510. self.deploy_lock = bb.utils.lockfile(lock_file_name)
  511. def deploy_dir_unlock(self):
  512. if self.deploy_lock is None:
  513. return
  514. bb.utils.unlockfile(self.deploy_lock)
  515. self.deploy_lock = None
  516. def construct_uris(self, uris, base_paths):
  517. """
  518. Construct URIs based on the following pattern: uri/base_path where 'uri'
  519. and 'base_path' correspond to each element of the corresponding array
  520. argument leading to len(uris) x len(base_paths) elements on the returned
  521. array
  522. """
  523. def _append(arr1, arr2, sep='/'):
  524. res = []
  525. narr1 = [a.rstrip(sep) for a in arr1]
  526. narr2 = [a.rstrip(sep).lstrip(sep) for a in arr2]
  527. for a1 in narr1:
  528. if arr2:
  529. for a2 in narr2:
  530. res.append("%s%s%s" % (a1, sep, a2))
  531. else:
  532. res.append(a1)
  533. return res
  534. return _append(uris, base_paths)
  535. def create_packages_dir(d, subrepo_dir, deploydir, taskname, filterbydependencies):
  536. """
  537. Go through our do_package_write_X dependencies and hardlink the packages we depend
  538. upon into the repo directory. This prevents us seeing other packages that may
  539. have been built that we don't depend upon and also packages for architectures we don't
  540. support.
  541. """
  542. import errno
  543. taskdepdata = d.getVar("BB_TASKDEPDATA", False)
  544. mytaskname = d.getVar("BB_RUNTASK")
  545. pn = d.getVar("PN")
  546. seendirs = set()
  547. multilibs = {}
  548. bb.utils.remove(subrepo_dir, recurse=True)
  549. bb.utils.mkdirhier(subrepo_dir)
  550. # Detect bitbake -b usage
  551. nodeps = d.getVar("BB_LIMITEDDEPS") or False
  552. if nodeps or not filterbydependencies:
  553. oe.path.symlink(deploydir, subrepo_dir, True)
  554. return
  555. start = None
  556. for dep in taskdepdata:
  557. data = taskdepdata[dep]
  558. if data[1] == mytaskname and data[0] == pn:
  559. start = dep
  560. break
  561. if start is None:
  562. bb.fatal("Couldn't find ourself in BB_TASKDEPDATA?")
  563. pkgdeps = set()
  564. start = [start]
  565. seen = set(start)
  566. # Support direct dependencies (do_rootfs -> do_package_write_X)
  567. # or indirect dependencies within PN (do_populate_sdk_ext -> do_rootfs -> do_package_write_X)
  568. while start:
  569. next = []
  570. for dep2 in start:
  571. for dep in taskdepdata[dep2][3]:
  572. if taskdepdata[dep][0] != pn:
  573. if "do_" + taskname in dep:
  574. pkgdeps.add(dep)
  575. elif dep not in seen:
  576. next.append(dep)
  577. seen.add(dep)
  578. start = next
  579. for dep in pkgdeps:
  580. c = taskdepdata[dep][0]
  581. manifest, d2 = oe.sstatesig.find_sstate_manifest(c, taskdepdata[dep][2], taskname, d, multilibs)
  582. if not manifest:
  583. bb.fatal("No manifest generated from: %s in %s" % (c, taskdepdata[dep][2]))
  584. if not os.path.exists(manifest):
  585. continue
  586. with open(manifest, "r") as f:
  587. for l in f:
  588. l = l.strip()
  589. deploydir = os.path.normpath(deploydir)
  590. if bb.data.inherits_class('packagefeed-stability', d):
  591. dest = l.replace(deploydir + "-prediff", "")
  592. else:
  593. dest = l.replace(deploydir, "")
  594. dest = subrepo_dir + dest
  595. if l.endswith("/"):
  596. if dest not in seendirs:
  597. bb.utils.mkdirhier(dest)
  598. seendirs.add(dest)
  599. continue
  600. # Try to hardlink the file, copy if that fails
  601. destdir = os.path.dirname(dest)
  602. if destdir not in seendirs:
  603. bb.utils.mkdirhier(destdir)
  604. seendirs.add(destdir)
  605. try:
  606. os.link(l, dest)
  607. except OSError as err:
  608. if err.errno == errno.EXDEV:
  609. bb.utils.copyfile(l, dest)
  610. else:
  611. raise
  612. class RpmPM(PackageManager):
  613. def __init__(self,
  614. d,
  615. target_rootfs,
  616. target_vendor,
  617. task_name='target',
  618. arch_var=None,
  619. os_var=None,
  620. rpm_repo_workdir="oe-rootfs-repo",
  621. filterbydependencies=True,
  622. needfeed=True):
  623. super(RpmPM, self).__init__(d, target_rootfs)
  624. self.target_vendor = target_vendor
  625. self.task_name = task_name
  626. if arch_var == None:
  627. self.archs = self.d.getVar('ALL_MULTILIB_PACKAGE_ARCHS').replace("-","_")
  628. else:
  629. self.archs = self.d.getVar(arch_var).replace("-","_")
  630. if task_name == "host":
  631. self.primary_arch = self.d.getVar('SDK_ARCH')
  632. else:
  633. self.primary_arch = self.d.getVar('MACHINE_ARCH')
  634. if needfeed:
  635. self.rpm_repo_dir = oe.path.join(self.d.getVar('WORKDIR'), rpm_repo_workdir)
  636. create_packages_dir(self.d, oe.path.join(self.rpm_repo_dir, "rpm"), d.getVar("DEPLOY_DIR_RPM"), "package_write_rpm", filterbydependencies)
  637. self.saved_packaging_data = self.d.expand('${T}/saved_packaging_data/%s' % self.task_name)
  638. if not os.path.exists(self.d.expand('${T}/saved_packaging_data')):
  639. bb.utils.mkdirhier(self.d.expand('${T}/saved_packaging_data'))
  640. self.packaging_data_dirs = ['etc/rpm', 'etc/rpmrc', 'etc/dnf', 'var/lib/rpm', 'var/lib/dnf', 'var/cache/dnf']
  641. self.solution_manifest = self.d.expand('${T}/saved/%s_solution' %
  642. self.task_name)
  643. if not os.path.exists(self.d.expand('${T}/saved')):
  644. bb.utils.mkdirhier(self.d.expand('${T}/saved'))
  645. def _configure_dnf(self):
  646. # libsolv handles 'noarch' internally, we don't need to specify it explicitly
  647. archs = [i for i in reversed(self.archs.split()) if i not in ["any", "all", "noarch"]]
  648. # This prevents accidental matching against libsolv's built-in policies
  649. if len(archs) <= 1:
  650. archs = archs + ["bogusarch"]
  651. confdir = "%s/%s" %(self.target_rootfs, "etc/dnf/vars/")
  652. bb.utils.mkdirhier(confdir)
  653. open(confdir + "arch", 'w').write(":".join(archs))
  654. distro_codename = self.d.getVar('DISTRO_CODENAME')
  655. open(confdir + "releasever", 'w').write(distro_codename if distro_codename is not None else '')
  656. open(oe.path.join(self.target_rootfs, "etc/dnf/dnf.conf"), 'w').write("")
  657. def _configure_rpm(self):
  658. # We need to configure rpm to use our primary package architecture as the installation architecture,
  659. # and to make it compatible with other package architectures that we use.
  660. # Otherwise it will refuse to proceed with packages installation.
  661. platformconfdir = "%s/%s" %(self.target_rootfs, "etc/rpm/")
  662. rpmrcconfdir = "%s/%s" %(self.target_rootfs, "etc/")
  663. bb.utils.mkdirhier(platformconfdir)
  664. open(platformconfdir + "platform", 'w').write("%s-pc-linux" % self.primary_arch)
  665. with open(rpmrcconfdir + "rpmrc", 'w') as f:
  666. f.write("arch_compat: %s: %s\n" % (self.primary_arch, self.archs if len(self.archs) > 0 else self.primary_arch))
  667. f.write("buildarch_compat: %s: noarch\n" % self.primary_arch)
  668. open(platformconfdir + "macros", 'w').write("%_transaction_color 7\n")
  669. if self.d.getVar('RPM_PREFER_ELF_ARCH'):
  670. open(platformconfdir + "macros", 'a').write("%%_prefer_color %s" % (self.d.getVar('RPM_PREFER_ELF_ARCH')))
  671. else:
  672. open(platformconfdir + "macros", 'a').write("%_prefer_color 7")
  673. if self.d.getVar('RPM_SIGN_PACKAGES') == '1':
  674. signer = get_signer(self.d, self.d.getVar('RPM_GPG_BACKEND'))
  675. pubkey_path = oe.path.join(self.d.getVar('B'), 'rpm-key')
  676. signer.export_pubkey(pubkey_path, self.d.getVar('RPM_GPG_NAME'))
  677. rpm_bin = bb.utils.which(os.getenv('PATH'), "rpmkeys")
  678. cmd = [rpm_bin, '--root=%s' % self.target_rootfs, '--import', pubkey_path]
  679. try:
  680. subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  681. except subprocess.CalledProcessError as e:
  682. bb.fatal("Importing GPG key failed. Command '%s' "
  683. "returned %d:\n%s" % (' '.join(cmd), e.returncode, e.output.decode("utf-8")))
  684. def create_configs(self):
  685. self._configure_dnf()
  686. self._configure_rpm()
  687. def write_index(self):
  688. lockfilename = self.d.getVar('DEPLOY_DIR_RPM') + "/rpm.lock"
  689. lf = bb.utils.lockfile(lockfilename, False)
  690. RpmIndexer(self.d, self.rpm_repo_dir).write_index()
  691. bb.utils.unlockfile(lf)
  692. def insert_feeds_uris(self, feed_uris, feed_base_paths, feed_archs):
  693. from urllib.parse import urlparse
  694. if feed_uris == "":
  695. return
  696. gpg_opts = ''
  697. if self.d.getVar('PACKAGE_FEED_SIGN') == '1':
  698. gpg_opts += 'repo_gpgcheck=1\n'
  699. gpg_opts += 'gpgkey=file://%s/pki/packagefeed-gpg/PACKAGEFEED-GPG-KEY-%s-%s\n' % (self.d.getVar('sysconfdir'), self.d.getVar('DISTRO'), self.d.getVar('DISTRO_CODENAME'))
  700. if self.d.getVar('RPM_SIGN_PACKAGES') != '1':
  701. gpg_opts += 'gpgcheck=0\n'
  702. bb.utils.mkdirhier(oe.path.join(self.target_rootfs, "etc", "yum.repos.d"))
  703. remote_uris = self.construct_uris(feed_uris.split(), feed_base_paths.split())
  704. for uri in remote_uris:
  705. repo_base = "oe-remote-repo" + "-".join(urlparse(uri).path.split("/"))
  706. if feed_archs is not None:
  707. for arch in feed_archs.split():
  708. repo_uri = uri + "/" + arch
  709. repo_id = "oe-remote-repo" + "-".join(urlparse(repo_uri).path.split("/"))
  710. repo_name = "OE Remote Repo:" + " ".join(urlparse(repo_uri).path.split("/"))
  711. open(oe.path.join(self.target_rootfs, "etc", "yum.repos.d", repo_base + ".repo"), 'a').write(
  712. "[%s]\nname=%s\nbaseurl=%s\n%s\n" % (repo_id, repo_name, repo_uri, gpg_opts))
  713. else:
  714. repo_name = "OE Remote Repo:" + " ".join(urlparse(uri).path.split("/"))
  715. repo_uri = uri
  716. open(oe.path.join(self.target_rootfs, "etc", "yum.repos.d", repo_base + ".repo"), 'w').write(
  717. "[%s]\nname=%s\nbaseurl=%s\n%s" % (repo_base, repo_name, repo_uri, gpg_opts))
  718. def _prepare_pkg_transaction(self):
  719. os.environ['D'] = self.target_rootfs
  720. os.environ['OFFLINE_ROOT'] = self.target_rootfs
  721. os.environ['IPKG_OFFLINE_ROOT'] = self.target_rootfs
  722. os.environ['OPKG_OFFLINE_ROOT'] = self.target_rootfs
  723. os.environ['INTERCEPT_DIR'] = self.intercepts_dir
  724. os.environ['NATIVE_ROOT'] = self.d.getVar('STAGING_DIR_NATIVE')
  725. def install(self, pkgs, attempt_only = False):
  726. if len(pkgs) == 0:
  727. return
  728. self._prepare_pkg_transaction()
  729. bad_recommendations = self.d.getVar('BAD_RECOMMENDATIONS')
  730. package_exclude = self.d.getVar('PACKAGE_EXCLUDE')
  731. exclude_pkgs = (bad_recommendations.split() if bad_recommendations else []) + (package_exclude.split() if package_exclude else [])
  732. output = self._invoke_dnf((["--skip-broken"] if attempt_only else []) +
  733. (["-x", ",".join(exclude_pkgs)] if len(exclude_pkgs) > 0 else []) +
  734. (["--setopt=install_weak_deps=False"] if self.d.getVar('NO_RECOMMENDATIONS') == "1" else []) +
  735. (["--nogpgcheck"] if self.d.getVar('RPM_SIGN_PACKAGES') != '1' else ["--setopt=gpgcheck=True"]) +
  736. ["install"] +
  737. pkgs)
  738. failed_scriptlets_pkgnames = collections.OrderedDict()
  739. for line in output.splitlines():
  740. if line.startswith("Error in POSTIN scriptlet in rpm package"):
  741. failed_scriptlets_pkgnames[line.split()[-1]] = True
  742. if len(failed_scriptlets_pkgnames) > 0:
  743. failed_postinsts_abort(list(failed_scriptlets_pkgnames.keys()), self.d.expand("${T}/log.do_${BB_CURRENTTASK}"))
  744. def remove(self, pkgs, with_dependencies = True):
  745. if not pkgs:
  746. return
  747. self._prepare_pkg_transaction()
  748. if with_dependencies:
  749. self._invoke_dnf(["remove"] + pkgs)
  750. else:
  751. cmd = bb.utils.which(os.getenv('PATH'), "rpm")
  752. args = ["-e", "-v", "--nodeps", "--root=%s" %self.target_rootfs]
  753. try:
  754. bb.note("Running %s" % ' '.join([cmd] + args + pkgs))
  755. output = subprocess.check_output([cmd] + args + pkgs, stderr=subprocess.STDOUT).decode("utf-8")
  756. bb.note(output)
  757. except subprocess.CalledProcessError as e:
  758. bb.fatal("Could not invoke rpm. Command "
  759. "'%s' returned %d:\n%s" % (' '.join([cmd] + args + pkgs), e.returncode, e.output.decode("utf-8")))
  760. def upgrade(self):
  761. self._prepare_pkg_transaction()
  762. self._invoke_dnf(["upgrade"])
  763. def autoremove(self):
  764. self._prepare_pkg_transaction()
  765. self._invoke_dnf(["autoremove"])
  766. def remove_packaging_data(self):
  767. self._invoke_dnf(["clean", "all"])
  768. for dir in self.packaging_data_dirs:
  769. bb.utils.remove(oe.path.join(self.target_rootfs, dir), True)
  770. def backup_packaging_data(self):
  771. # Save the packaging dirs for increment rpm image generation
  772. if os.path.exists(self.saved_packaging_data):
  773. bb.utils.remove(self.saved_packaging_data, True)
  774. for i in self.packaging_data_dirs:
  775. source_dir = oe.path.join(self.target_rootfs, i)
  776. target_dir = oe.path.join(self.saved_packaging_data, i)
  777. if os.path.isdir(source_dir):
  778. shutil.copytree(source_dir, target_dir, symlinks=True)
  779. elif os.path.isfile(source_dir):
  780. shutil.copy2(source_dir, target_dir)
  781. def recovery_packaging_data(self):
  782. # Move the rpmlib back
  783. if os.path.exists(self.saved_packaging_data):
  784. for i in self.packaging_data_dirs:
  785. target_dir = oe.path.join(self.target_rootfs, i)
  786. if os.path.exists(target_dir):
  787. bb.utils.remove(target_dir, True)
  788. source_dir = oe.path.join(self.saved_packaging_data, i)
  789. if os.path.isdir(source_dir):
  790. shutil.copytree(source_dir, target_dir, symlinks=True)
  791. elif os.path.isfile(source_dir):
  792. shutil.copy2(source_dir, target_dir)
  793. def list_installed(self):
  794. output = self._invoke_dnf(["repoquery", "--installed", "--queryformat", "Package: %{name} %{arch} %{version} %{name}-%{version}-%{release}.%{arch}.rpm\nDependencies:\n%{requires}\nRecommendations:\n%{recommends}\nDependenciesEndHere:\n"],
  795. print_output = False)
  796. packages = {}
  797. current_package = None
  798. current_deps = None
  799. current_state = "initial"
  800. for line in output.splitlines():
  801. if line.startswith("Package:"):
  802. package_info = line.split(" ")[1:]
  803. current_package = package_info[0]
  804. package_arch = package_info[1]
  805. package_version = package_info[2]
  806. package_rpm = package_info[3]
  807. packages[current_package] = {"arch":package_arch, "ver":package_version, "filename":package_rpm}
  808. current_deps = []
  809. elif line.startswith("Dependencies:"):
  810. current_state = "dependencies"
  811. elif line.startswith("Recommendations"):
  812. current_state = "recommendations"
  813. elif line.startswith("DependenciesEndHere:"):
  814. current_state = "initial"
  815. packages[current_package]["deps"] = current_deps
  816. elif len(line) > 0:
  817. if current_state == "dependencies":
  818. current_deps.append(line)
  819. elif current_state == "recommendations":
  820. current_deps.append("%s [REC]" % line)
  821. return packages
  822. def update(self):
  823. self._invoke_dnf(["makecache", "--refresh"])
  824. def _invoke_dnf(self, dnf_args, fatal = True, print_output = True ):
  825. os.environ['RPM_ETCCONFIGDIR'] = self.target_rootfs
  826. dnf_cmd = bb.utils.which(os.getenv('PATH'), "dnf")
  827. standard_dnf_args = ["-v", "--rpmverbosity=info", "-y",
  828. "-c", oe.path.join(self.target_rootfs, "etc/dnf/dnf.conf"),
  829. "--setopt=reposdir=%s" %(oe.path.join(self.target_rootfs, "etc/yum.repos.d")),
  830. "--installroot=%s" % (self.target_rootfs),
  831. "--setopt=logdir=%s" % (self.d.getVar('T'))
  832. ]
  833. if hasattr(self, "rpm_repo_dir"):
  834. standard_dnf_args.append("--repofrompath=oe-repo,%s" % (self.rpm_repo_dir))
  835. cmd = [dnf_cmd] + standard_dnf_args + dnf_args
  836. bb.note('Running %s' % ' '.join(cmd))
  837. try:
  838. output = subprocess.check_output(cmd,stderr=subprocess.STDOUT).decode("utf-8")
  839. if print_output:
  840. bb.debug(1, output)
  841. return output
  842. except subprocess.CalledProcessError as e:
  843. if print_output:
  844. (bb.note, bb.fatal)[fatal]("Could not invoke dnf. Command "
  845. "'%s' returned %d:\n%s" % (' '.join(cmd), e.returncode, e.output.decode("utf-8")))
  846. else:
  847. (bb.note, bb.fatal)[fatal]("Could not invoke dnf. Command "
  848. "'%s' returned %d:" % (' '.join(cmd), e.returncode))
  849. return e.output.decode("utf-8")
  850. def dump_install_solution(self, pkgs):
  851. open(self.solution_manifest, 'w').write(" ".join(pkgs))
  852. return pkgs
  853. def load_old_install_solution(self):
  854. if not os.path.exists(self.solution_manifest):
  855. return []
  856. return open(self.solution_manifest, 'r').read().split()
  857. def _script_num_prefix(self, path):
  858. files = os.listdir(path)
  859. numbers = set()
  860. numbers.add(99)
  861. for f in files:
  862. numbers.add(int(f.split("-")[0]))
  863. return max(numbers) + 1
  864. def save_rpmpostinst(self, pkg):
  865. bb.note("Saving postinstall script of %s" % (pkg))
  866. cmd = bb.utils.which(os.getenv('PATH'), "rpm")
  867. args = ["-q", "--root=%s" % self.target_rootfs, "--queryformat", "%{postin}", pkg]
  868. try:
  869. output = subprocess.check_output([cmd] + args,stderr=subprocess.STDOUT).decode("utf-8")
  870. except subprocess.CalledProcessError as e:
  871. bb.fatal("Could not invoke rpm. Command "
  872. "'%s' returned %d:\n%s" % (' '.join([cmd] + args), e.returncode, e.output.decode("utf-8")))
  873. # may need to prepend #!/bin/sh to output
  874. target_path = oe.path.join(self.target_rootfs, self.d.expand('${sysconfdir}/rpm-postinsts/'))
  875. bb.utils.mkdirhier(target_path)
  876. num = self._script_num_prefix(target_path)
  877. saved_script_name = oe.path.join(target_path, "%d-%s" % (num, pkg))
  878. open(saved_script_name, 'w').write(output)
  879. os.chmod(saved_script_name, 0o755)
  880. def _handle_intercept_failure(self, registered_pkgs):
  881. rpm_postinsts_dir = self.target_rootfs + self.d.expand('${sysconfdir}/rpm-postinsts/')
  882. bb.utils.mkdirhier(rpm_postinsts_dir)
  883. # Save the package postinstalls in /etc/rpm-postinsts
  884. for pkg in registered_pkgs.split():
  885. self.save_rpmpostinst(pkg)
  886. def extract(self, pkg):
  887. output = self._invoke_dnf(["repoquery", "--queryformat", "%{location}", pkg])
  888. pkg_name = output.splitlines()[-1]
  889. if not pkg_name.endswith(".rpm"):
  890. bb.fatal("dnf could not find package %s in repository: %s" %(pkg, output))
  891. pkg_path = oe.path.join(self.rpm_repo_dir, pkg_name)
  892. cpio_cmd = bb.utils.which(os.getenv("PATH"), "cpio")
  893. rpm2cpio_cmd = bb.utils.which(os.getenv("PATH"), "rpm2cpio")
  894. if not os.path.isfile(pkg_path):
  895. bb.fatal("Unable to extract package for '%s'."
  896. "File %s doesn't exists" % (pkg, pkg_path))
  897. tmp_dir = tempfile.mkdtemp()
  898. current_dir = os.getcwd()
  899. os.chdir(tmp_dir)
  900. try:
  901. cmd = "%s %s | %s -idmv" % (rpm2cpio_cmd, pkg_path, cpio_cmd)
  902. output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
  903. except subprocess.CalledProcessError as e:
  904. bb.utils.remove(tmp_dir, recurse=True)
  905. bb.fatal("Unable to extract %s package. Command '%s' "
  906. "returned %d:\n%s" % (pkg_path, cmd, e.returncode, e.output.decode("utf-8")))
  907. except OSError as e:
  908. bb.utils.remove(tmp_dir, recurse=True)
  909. bb.fatal("Unable to extract %s package. Command '%s' "
  910. "returned %d:\n%s at %s" % (pkg_path, cmd, e.errno, e.strerror, e.filename))
  911. bb.note("Extracted %s to %s" % (pkg_path, tmp_dir))
  912. os.chdir(current_dir)
  913. return tmp_dir
  914. class OpkgDpkgPM(PackageManager):
  915. def __init__(self, d, target_rootfs):
  916. """
  917. This is an abstract class. Do not instantiate this directly.
  918. """
  919. super(OpkgDpkgPM, self).__init__(d, target_rootfs)
  920. def package_info(self, pkg, cmd):
  921. """
  922. Returns a dictionary with the package info.
  923. This method extracts the common parts for Opkg and Dpkg
  924. """
  925. try:
  926. output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True).decode("utf-8")
  927. except subprocess.CalledProcessError as e:
  928. bb.fatal("Unable to list available packages. Command '%s' "
  929. "returned %d:\n%s" % (cmd, e.returncode, e.output.decode("utf-8")))
  930. return opkg_query(output)
  931. def extract(self, pkg, pkg_info):
  932. """
  933. Returns the path to a tmpdir where resides the contents of a package.
  934. Deleting the tmpdir is responsability of the caller.
  935. This method extracts the common parts for Opkg and Dpkg
  936. """
  937. ar_cmd = bb.utils.which(os.getenv("PATH"), "ar")
  938. tar_cmd = bb.utils.which(os.getenv("PATH"), "tar")
  939. pkg_path = pkg_info[pkg]["filepath"]
  940. if not os.path.isfile(pkg_path):
  941. bb.fatal("Unable to extract package for '%s'."
  942. "File %s doesn't exists" % (pkg, pkg_path))
  943. tmp_dir = tempfile.mkdtemp()
  944. current_dir = os.getcwd()
  945. os.chdir(tmp_dir)
  946. data_tar = 'data.tar.xz'
  947. try:
  948. cmd = [ar_cmd, 'x', pkg_path]
  949. output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  950. cmd = [tar_cmd, 'xf', data_tar]
  951. output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  952. except subprocess.CalledProcessError as e:
  953. bb.utils.remove(tmp_dir, recurse=True)
  954. bb.fatal("Unable to extract %s package. Command '%s' "
  955. "returned %d:\n%s" % (pkg_path, ' '.join(cmd), e.returncode, e.output.decode("utf-8")))
  956. except OSError as e:
  957. bb.utils.remove(tmp_dir, recurse=True)
  958. bb.fatal("Unable to extract %s package. Command '%s' "
  959. "returned %d:\n%s at %s" % (pkg_path, ' '.join(cmd), e.errno, e.strerror, e.filename))
  960. bb.note("Extracted %s to %s" % (pkg_path, tmp_dir))
  961. bb.utils.remove(os.path.join(tmp_dir, "debian-binary"))
  962. bb.utils.remove(os.path.join(tmp_dir, "control.tar.gz"))
  963. os.chdir(current_dir)
  964. return tmp_dir
  965. def _handle_intercept_failure(self, registered_pkgs):
  966. self.mark_packages("unpacked", registered_pkgs.split())
  967. class OpkgPM(OpkgDpkgPM):
  968. def __init__(self, d, target_rootfs, config_file, archs, task_name='target', ipk_repo_workdir="oe-rootfs-repo", filterbydependencies=True, prepare_index=True):
  969. super(OpkgPM, self).__init__(d, target_rootfs)
  970. self.config_file = config_file
  971. self.pkg_archs = archs
  972. self.task_name = task_name
  973. self.deploy_dir = oe.path.join(self.d.getVar('WORKDIR'), ipk_repo_workdir)
  974. self.deploy_lock_file = os.path.join(self.deploy_dir, "deploy.lock")
  975. self.opkg_cmd = bb.utils.which(os.getenv('PATH'), "opkg")
  976. self.opkg_args = "--volatile-cache -f %s -t %s -o %s " % (self.config_file, self.d.expand('${T}/ipktemp/') ,target_rootfs)
  977. self.opkg_args += self.d.getVar("OPKG_ARGS")
  978. if prepare_index:
  979. create_packages_dir(self.d, self.deploy_dir, d.getVar("DEPLOY_DIR_IPK"), "package_write_ipk", filterbydependencies)
  980. opkg_lib_dir = self.d.getVar('OPKGLIBDIR')
  981. if opkg_lib_dir[0] == "/":
  982. opkg_lib_dir = opkg_lib_dir[1:]
  983. self.opkg_dir = os.path.join(target_rootfs, opkg_lib_dir, "opkg")
  984. bb.utils.mkdirhier(self.opkg_dir)
  985. self.saved_opkg_dir = self.d.expand('${T}/saved/%s' % self.task_name)
  986. if not os.path.exists(self.d.expand('${T}/saved')):
  987. bb.utils.mkdirhier(self.d.expand('${T}/saved'))
  988. self.from_feeds = (self.d.getVar('BUILD_IMAGES_FROM_FEEDS') or "") == "1"
  989. if self.from_feeds:
  990. self._create_custom_config()
  991. else:
  992. self._create_config()
  993. self.indexer = OpkgIndexer(self.d, self.deploy_dir)
  994. def mark_packages(self, status_tag, packages=None):
  995. """
  996. This function will change a package's status in /var/lib/opkg/status file.
  997. If 'packages' is None then the new_status will be applied to all
  998. packages
  999. """
  1000. status_file = os.path.join(self.opkg_dir, "status")
  1001. with open(status_file, "r") as sf:
  1002. with open(status_file + ".tmp", "w+") as tmp_sf:
  1003. if packages is None:
  1004. tmp_sf.write(re.sub(r"Package: (.*?)\n((?:[^\n]+\n)*?)Status: (.*)(?:unpacked|installed)",
  1005. r"Package: \1\n\2Status: \3%s" % status_tag,
  1006. sf.read()))
  1007. else:
  1008. if type(packages).__name__ != "list":
  1009. raise TypeError("'packages' should be a list object")
  1010. status = sf.read()
  1011. for pkg in packages:
  1012. status = re.sub(r"Package: %s\n((?:[^\n]+\n)*?)Status: (.*)(?:unpacked|installed)" % pkg,
  1013. r"Package: %s\n\1Status: \2%s" % (pkg, status_tag),
  1014. status)
  1015. tmp_sf.write(status)
  1016. os.rename(status_file + ".tmp", status_file)
  1017. def _create_custom_config(self):
  1018. bb.note("Building from feeds activated!")
  1019. with open(self.config_file, "w+") as config_file:
  1020. priority = 1
  1021. for arch in self.pkg_archs.split():
  1022. config_file.write("arch %s %d\n" % (arch, priority))
  1023. priority += 5
  1024. for line in (self.d.getVar('IPK_FEED_URIS') or "").split():
  1025. feed_match = re.match(r"^[ \t]*(.*)##([^ \t]*)[ \t]*$", line)
  1026. if feed_match is not None:
  1027. feed_name = feed_match.group(1)
  1028. feed_uri = feed_match.group(2)
  1029. bb.note("Add %s feed with URL %s" % (feed_name, feed_uri))
  1030. config_file.write("src/gz %s %s\n" % (feed_name, feed_uri))
  1031. """
  1032. Allow to use package deploy directory contents as quick devel-testing
  1033. feed. This creates individual feed configs for each arch subdir of those
  1034. specified as compatible for the current machine.
  1035. NOTE: Development-helper feature, NOT a full-fledged feed.
  1036. """
  1037. if (self.d.getVar('FEED_DEPLOYDIR_BASE_URI') or "") != "":
  1038. for arch in self.pkg_archs.split():
  1039. cfg_file_name = os.path.join(self.target_rootfs,
  1040. self.d.getVar("sysconfdir"),
  1041. "opkg",
  1042. "local-%s-feed.conf" % arch)
  1043. with open(cfg_file_name, "w+") as cfg_file:
  1044. cfg_file.write("src/gz local-%s %s/%s" %
  1045. (arch,
  1046. self.d.getVar('FEED_DEPLOYDIR_BASE_URI'),
  1047. arch))
  1048. if self.d.getVar('OPKGLIBDIR') != '/var/lib':
  1049. # There is no command line option for this anymore, we need to add
  1050. # info_dir and status_file to config file, if OPKGLIBDIR doesn't have
  1051. # the default value of "/var/lib" as defined in opkg:
  1052. # libopkg/opkg_conf.h:#define OPKG_CONF_DEFAULT_LISTS_DIR VARDIR "/lib/opkg/lists"
  1053. # libopkg/opkg_conf.h:#define OPKG_CONF_DEFAULT_INFO_DIR VARDIR "/lib/opkg/info"
  1054. # libopkg/opkg_conf.h:#define OPKG_CONF_DEFAULT_STATUS_FILE VARDIR "/lib/opkg/status"
  1055. cfg_file.write("option info_dir %s\n" % os.path.join(self.d.getVar('OPKGLIBDIR'), 'opkg', 'info'))
  1056. cfg_file.write("option lists_dir %s\n" % os.path.join(self.d.getVar('OPKGLIBDIR'), 'opkg', 'lists'))
  1057. cfg_file.write("option status_file %s\n" % os.path.join(self.d.getVar('OPKGLIBDIR'), 'opkg', 'status'))
  1058. def _create_config(self):
  1059. with open(self.config_file, "w+") as config_file:
  1060. priority = 1
  1061. for arch in self.pkg_archs.split():
  1062. config_file.write("arch %s %d\n" % (arch, priority))
  1063. priority += 5
  1064. config_file.write("src oe file:%s\n" % self.deploy_dir)
  1065. for arch in self.pkg_archs.split():
  1066. pkgs_dir = os.path.join(self.deploy_dir, arch)
  1067. if os.path.isdir(pkgs_dir):
  1068. config_file.write("src oe-%s file:%s\n" %
  1069. (arch, pkgs_dir))
  1070. if self.d.getVar('OPKGLIBDIR') != '/var/lib':
  1071. # There is no command line option for this anymore, we need to add
  1072. # info_dir and status_file to config file, if OPKGLIBDIR doesn't have
  1073. # the default value of "/var/lib" as defined in opkg:
  1074. # libopkg/opkg_conf.h:#define OPKG_CONF_DEFAULT_LISTS_DIR VARDIR "/lib/opkg/lists"
  1075. # libopkg/opkg_conf.h:#define OPKG_CONF_DEFAULT_INFO_DIR VARDIR "/lib/opkg/info"
  1076. # libopkg/opkg_conf.h:#define OPKG_CONF_DEFAULT_STATUS_FILE VARDIR "/lib/opkg/status"
  1077. config_file.write("option info_dir %s\n" % os.path.join(self.d.getVar('OPKGLIBDIR'), 'opkg', 'info'))
  1078. config_file.write("option lists_dir %s\n" % os.path.join(self.d.getVar('OPKGLIBDIR'), 'opkg', 'lists'))
  1079. config_file.write("option status_file %s\n" % os.path.join(self.d.getVar('OPKGLIBDIR'), 'opkg', 'status'))
  1080. def insert_feeds_uris(self, feed_uris, feed_base_paths, feed_archs):
  1081. if feed_uris == "":
  1082. return
  1083. rootfs_config = os.path.join('%s/etc/opkg/base-feeds.conf'
  1084. % self.target_rootfs)
  1085. feed_uris = self.construct_uris(feed_uris.split(), feed_base_paths.split())
  1086. archs = self.pkg_archs.split() if feed_archs is None else feed_archs.split()
  1087. with open(rootfs_config, "w+") as config_file:
  1088. uri_iterator = 0
  1089. for uri in feed_uris:
  1090. if archs:
  1091. for arch in archs:
  1092. if (feed_archs is None) and (not os.path.exists(oe.path.join(self.deploy_dir, arch))):
  1093. continue
  1094. bb.note('Adding opkg feed url-%s-%d (%s)' %
  1095. (arch, uri_iterator, uri))
  1096. config_file.write("src/gz uri-%s-%d %s/%s\n" %
  1097. (arch, uri_iterator, uri, arch))
  1098. else:
  1099. bb.note('Adding opkg feed url-%d (%s)' %
  1100. (uri_iterator, uri))
  1101. config_file.write("src/gz uri-%d %s\n" %
  1102. (uri_iterator, uri))
  1103. uri_iterator += 1
  1104. def update(self):
  1105. self.deploy_dir_lock()
  1106. cmd = "%s %s update" % (self.opkg_cmd, self.opkg_args)
  1107. try:
  1108. subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT)
  1109. except subprocess.CalledProcessError as e:
  1110. self.deploy_dir_unlock()
  1111. bb.fatal("Unable to update the package index files. Command '%s' "
  1112. "returned %d:\n%s" % (cmd, e.returncode, e.output.decode("utf-8")))
  1113. self.deploy_dir_unlock()
  1114. def install(self, pkgs, attempt_only=False):
  1115. if not pkgs:
  1116. return
  1117. cmd = "%s %s" % (self.opkg_cmd, self.opkg_args)
  1118. for exclude in (self.d.getVar("PACKAGE_EXCLUDE") or "").split():
  1119. cmd += " --add-exclude %s" % exclude
  1120. for bad_recommendation in (self.d.getVar("BAD_RECOMMENDATIONS") or "").split():
  1121. cmd += " --add-ignore-recommends %s" % bad_recommendation
  1122. cmd += " install "
  1123. cmd += " ".join(pkgs)
  1124. os.environ['D'] = self.target_rootfs
  1125. os.environ['OFFLINE_ROOT'] = self.target_rootfs
  1126. os.environ['IPKG_OFFLINE_ROOT'] = self.target_rootfs
  1127. os.environ['OPKG_OFFLINE_ROOT'] = self.target_rootfs
  1128. os.environ['INTERCEPT_DIR'] = self.intercepts_dir
  1129. os.environ['NATIVE_ROOT'] = self.d.getVar('STAGING_DIR_NATIVE')
  1130. try:
  1131. bb.note("Installing the following packages: %s" % ' '.join(pkgs))
  1132. bb.note(cmd)
  1133. output = subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT).decode("utf-8")
  1134. bb.note(output)
  1135. failed_pkgs = []
  1136. for line in output.split('\n'):
  1137. if line.endswith("configuration required on target."):
  1138. bb.warn(line)
  1139. failed_pkgs.append(line.split(".")[0])
  1140. if failed_pkgs:
  1141. failed_postinsts_abort(failed_pkgs, self.d.expand("${T}/log.do_${BB_CURRENTTASK}"))
  1142. except subprocess.CalledProcessError as e:
  1143. (bb.fatal, bb.warn)[attempt_only]("Unable to install packages. "
  1144. "Command '%s' returned %d:\n%s" %
  1145. (cmd, e.returncode, e.output.decode("utf-8")))
  1146. def remove(self, pkgs, with_dependencies=True):
  1147. if not pkgs:
  1148. return
  1149. if with_dependencies:
  1150. cmd = "%s %s --force-remove --force-removal-of-dependent-packages remove %s" % \
  1151. (self.opkg_cmd, self.opkg_args, ' '.join(pkgs))
  1152. else:
  1153. cmd = "%s %s --force-depends remove %s" % \
  1154. (self.opkg_cmd, self.opkg_args, ' '.join(pkgs))
  1155. try:
  1156. bb.note(cmd)
  1157. output = subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT).decode("utf-8")
  1158. bb.note(output)
  1159. except subprocess.CalledProcessError as e:
  1160. bb.fatal("Unable to remove packages. Command '%s' "
  1161. "returned %d:\n%s" % (e.cmd, e.returncode, e.output.decode("utf-8")))
  1162. def write_index(self):
  1163. self.deploy_dir_lock()
  1164. result = self.indexer.write_index()
  1165. self.deploy_dir_unlock()
  1166. if result is not None:
  1167. bb.fatal(result)
  1168. def remove_packaging_data(self):
  1169. bb.utils.remove(self.opkg_dir, True)
  1170. # create the directory back, it's needed by PM lock
  1171. bb.utils.mkdirhier(self.opkg_dir)
  1172. def remove_lists(self):
  1173. if not self.from_feeds:
  1174. bb.utils.remove(os.path.join(self.opkg_dir, "lists"), True)
  1175. def list_installed(self):
  1176. return OpkgPkgsList(self.d, self.target_rootfs, self.config_file).list_pkgs()
  1177. def dummy_install(self, pkgs):
  1178. """
  1179. The following function dummy installs pkgs and returns the log of output.
  1180. """
  1181. if len(pkgs) == 0:
  1182. return
  1183. # Create an temp dir as opkg root for dummy installation
  1184. temp_rootfs = self.d.expand('${T}/opkg')
  1185. opkg_lib_dir = self.d.getVar('OPKGLIBDIR')
  1186. if opkg_lib_dir[0] == "/":
  1187. opkg_lib_dir = opkg_lib_dir[1:]
  1188. temp_opkg_dir = os.path.join(temp_rootfs, opkg_lib_dir, 'opkg')
  1189. bb.utils.mkdirhier(temp_opkg_dir)
  1190. opkg_args = "-f %s -o %s " % (self.config_file, temp_rootfs)
  1191. opkg_args += self.d.getVar("OPKG_ARGS")
  1192. cmd = "%s %s update" % (self.opkg_cmd, opkg_args)
  1193. try:
  1194. subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
  1195. except subprocess.CalledProcessError as e:
  1196. bb.fatal("Unable to update. Command '%s' "
  1197. "returned %d:\n%s" % (cmd, e.returncode, e.output.decode("utf-8")))
  1198. # Dummy installation
  1199. cmd = "%s %s --noaction install %s " % (self.opkg_cmd,
  1200. opkg_args,
  1201. ' '.join(pkgs))
  1202. try:
  1203. output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
  1204. except subprocess.CalledProcessError as e:
  1205. bb.fatal("Unable to dummy install packages. Command '%s' "
  1206. "returned %d:\n%s" % (cmd, e.returncode, e.output.decode("utf-8")))
  1207. bb.utils.remove(temp_rootfs, True)
  1208. return output
  1209. def backup_packaging_data(self):
  1210. # Save the opkglib for increment ipk image generation
  1211. if os.path.exists(self.saved_opkg_dir):
  1212. bb.utils.remove(self.saved_opkg_dir, True)
  1213. shutil.copytree(self.opkg_dir,
  1214. self.saved_opkg_dir,
  1215. symlinks=True)
  1216. def recover_packaging_data(self):
  1217. # Move the opkglib back
  1218. if os.path.exists(self.saved_opkg_dir):
  1219. if os.path.exists(self.opkg_dir):
  1220. bb.utils.remove(self.opkg_dir, True)
  1221. bb.note('Recover packaging data')
  1222. shutil.copytree(self.saved_opkg_dir,
  1223. self.opkg_dir,
  1224. symlinks=True)
  1225. def package_info(self, pkg):
  1226. """
  1227. Returns a dictionary with the package info.
  1228. """
  1229. cmd = "%s %s info %s" % (self.opkg_cmd, self.opkg_args, pkg)
  1230. pkg_info = super(OpkgPM, self).package_info(pkg, cmd)
  1231. pkg_arch = pkg_info[pkg]["arch"]
  1232. pkg_filename = pkg_info[pkg]["filename"]
  1233. pkg_info[pkg]["filepath"] = \
  1234. os.path.join(self.deploy_dir, pkg_arch, pkg_filename)
  1235. return pkg_info
  1236. def extract(self, pkg):
  1237. """
  1238. Returns the path to a tmpdir where resides the contents of a package.
  1239. Deleting the tmpdir is responsability of the caller.
  1240. """
  1241. pkg_info = self.package_info(pkg)
  1242. if not pkg_info:
  1243. bb.fatal("Unable to get information for package '%s' while "
  1244. "trying to extract the package." % pkg)
  1245. tmp_dir = super(OpkgPM, self).extract(pkg, pkg_info)
  1246. bb.utils.remove(os.path.join(tmp_dir, "data.tar.xz"))
  1247. return tmp_dir
  1248. class DpkgPM(OpkgDpkgPM):
  1249. def __init__(self, d, target_rootfs, archs, base_archs, apt_conf_dir=None, deb_repo_workdir="oe-rootfs-repo", filterbydependencies=True):
  1250. super(DpkgPM, self).__init__(d, target_rootfs)
  1251. self.deploy_dir = oe.path.join(self.d.getVar('WORKDIR'), deb_repo_workdir)
  1252. create_packages_dir(self.d, self.deploy_dir, d.getVar("DEPLOY_DIR_DEB"), "package_write_deb", filterbydependencies)
  1253. if apt_conf_dir is None:
  1254. self.apt_conf_dir = self.d.expand("${APTCONF_TARGET}/apt")
  1255. else:
  1256. self.apt_conf_dir = apt_conf_dir
  1257. self.apt_conf_file = os.path.join(self.apt_conf_dir, "apt.conf")
  1258. self.apt_get_cmd = bb.utils.which(os.getenv('PATH'), "apt-get")
  1259. self.apt_cache_cmd = bb.utils.which(os.getenv('PATH'), "apt-cache")
  1260. self.apt_args = d.getVar("APT_ARGS")
  1261. self.all_arch_list = archs.split()
  1262. all_mlb_pkg_arch_list = (self.d.getVar('ALL_MULTILIB_PACKAGE_ARCHS') or "").split()
  1263. self.all_arch_list.extend(arch for arch in all_mlb_pkg_arch_list if arch not in self.all_arch_list)
  1264. self._create_configs(archs, base_archs)
  1265. self.indexer = DpkgIndexer(self.d, self.deploy_dir)
  1266. def mark_packages(self, status_tag, packages=None):
  1267. """
  1268. This function will change a package's status in /var/lib/dpkg/status file.
  1269. If 'packages' is None then the new_status will be applied to all
  1270. packages
  1271. """
  1272. status_file = self.target_rootfs + "/var/lib/dpkg/status"
  1273. with open(status_file, "r") as sf:
  1274. with open(status_file + ".tmp", "w+") as tmp_sf:
  1275. if packages is None:
  1276. tmp_sf.write(re.sub(r"Package: (.*?)\n((?:[^\n]+\n)*?)Status: (.*)(?:unpacked|installed)",
  1277. r"Package: \1\n\2Status: \3%s" % status_tag,
  1278. sf.read()))
  1279. else:
  1280. if type(packages).__name__ != "list":
  1281. raise TypeError("'packages' should be a list object")
  1282. status = sf.read()
  1283. for pkg in packages:
  1284. status = re.sub(r"Package: %s\n((?:[^\n]+\n)*?)Status: (.*)(?:unpacked|installed)" % pkg,
  1285. r"Package: %s\n\1Status: \2%s" % (pkg, status_tag),
  1286. status)
  1287. tmp_sf.write(status)
  1288. os.rename(status_file + ".tmp", status_file)
  1289. def run_pre_post_installs(self, package_name=None):
  1290. """
  1291. Run the pre/post installs for package "package_name". If package_name is
  1292. None, then run all pre/post install scriptlets.
  1293. """
  1294. info_dir = self.target_rootfs + "/var/lib/dpkg/info"
  1295. ControlScript = collections.namedtuple("ControlScript", ["suffix", "name", "argument"])
  1296. control_scripts = [
  1297. ControlScript(".preinst", "Preinstall", "install"),
  1298. ControlScript(".postinst", "Postinstall", "configure")]
  1299. status_file = self.target_rootfs + "/var/lib/dpkg/status"
  1300. installed_pkgs = []
  1301. with open(status_file, "r") as status:
  1302. for line in status.read().split('\n'):
  1303. m = re.match(r"^Package: (.*)", line)
  1304. if m is not None:
  1305. installed_pkgs.append(m.group(1))
  1306. if package_name is not None and not package_name in installed_pkgs:
  1307. return
  1308. os.environ['D'] = self.target_rootfs
  1309. os.environ['OFFLINE_ROOT'] = self.target_rootfs
  1310. os.environ['IPKG_OFFLINE_ROOT'] = self.target_rootfs
  1311. os.environ['OPKG_OFFLINE_ROOT'] = self.target_rootfs
  1312. os.environ['INTERCEPT_DIR'] = self.intercepts_dir
  1313. os.environ['NATIVE_ROOT'] = self.d.getVar('STAGING_DIR_NATIVE')
  1314. for pkg_name in installed_pkgs:
  1315. for control_script in control_scripts:
  1316. p_full = os.path.join(info_dir, pkg_name + control_script.suffix)
  1317. if os.path.exists(p_full):
  1318. try:
  1319. bb.note("Executing %s for package: %s ..." %
  1320. (control_script.name.lower(), pkg_name))
  1321. output = subprocess.check_output([p_full, control_script.argument],
  1322. stderr=subprocess.STDOUT).decode("utf-8")
  1323. bb.note(output)
  1324. except subprocess.CalledProcessError as e:
  1325. bb.warn("%s for package %s failed with %d:\n%s" %
  1326. (control_script.name, pkg_name, e.returncode,
  1327. e.output.decode("utf-8")))
  1328. failed_postinsts_abort([pkg_name], self.d.expand("${T}/log.do_${BB_CURRENTTASK}"))
  1329. def update(self):
  1330. os.environ['APT_CONFIG'] = self.apt_conf_file
  1331. self.deploy_dir_lock()
  1332. cmd = "%s update" % self.apt_get_cmd
  1333. try:
  1334. subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT)
  1335. except subprocess.CalledProcessError as e:
  1336. bb.fatal("Unable to update the package index files. Command '%s' "
  1337. "returned %d:\n%s" % (e.cmd, e.returncode, e.output.decode("utf-8")))
  1338. self.deploy_dir_unlock()
  1339. def install(self, pkgs, attempt_only=False):
  1340. if attempt_only and len(pkgs) == 0:
  1341. return
  1342. os.environ['APT_CONFIG'] = self.apt_conf_file
  1343. cmd = "%s %s install --force-yes --allow-unauthenticated %s" % \
  1344. (self.apt_get_cmd, self.apt_args, ' '.join(pkgs))
  1345. try:
  1346. bb.note("Installing the following packages: %s" % ' '.join(pkgs))
  1347. subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT)
  1348. except subprocess.CalledProcessError as e:
  1349. (bb.fatal, bb.warn)[attempt_only]("Unable to install packages. "
  1350. "Command '%s' returned %d:\n%s" %
  1351. (cmd, e.returncode, e.output.decode("utf-8")))
  1352. # rename *.dpkg-new files/dirs
  1353. for root, dirs, files in os.walk(self.target_rootfs):
  1354. for dir in dirs:
  1355. new_dir = re.sub(r"\.dpkg-new", "", dir)
  1356. if dir != new_dir:
  1357. os.rename(os.path.join(root, dir),
  1358. os.path.join(root, new_dir))
  1359. for file in files:
  1360. new_file = re.sub(r"\.dpkg-new", "", file)
  1361. if file != new_file:
  1362. os.rename(os.path.join(root, file),
  1363. os.path.join(root, new_file))
  1364. def remove(self, pkgs, with_dependencies=True):
  1365. if not pkgs:
  1366. return
  1367. if with_dependencies:
  1368. os.environ['APT_CONFIG'] = self.apt_conf_file
  1369. cmd = "%s purge %s" % (self.apt_get_cmd, ' '.join(pkgs))
  1370. else:
  1371. cmd = "%s --admindir=%s/var/lib/dpkg --instdir=%s" \
  1372. " -P --force-depends %s" % \
  1373. (bb.utils.which(os.getenv('PATH'), "dpkg"),
  1374. self.target_rootfs, self.target_rootfs, ' '.join(pkgs))
  1375. try:
  1376. subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT)
  1377. except subprocess.CalledProcessError as e:
  1378. bb.fatal("Unable to remove packages. Command '%s' "
  1379. "returned %d:\n%s" % (e.cmd, e.returncode, e.output.decode("utf-8")))
  1380. def write_index(self):
  1381. self.deploy_dir_lock()
  1382. result = self.indexer.write_index()
  1383. self.deploy_dir_unlock()
  1384. if result is not None:
  1385. bb.fatal(result)
  1386. def insert_feeds_uris(self, feed_uris, feed_base_paths, feed_archs):
  1387. if feed_uris == "":
  1388. return
  1389. sources_conf = os.path.join("%s/etc/apt/sources.list"
  1390. % self.target_rootfs)
  1391. arch_list = []
  1392. if feed_archs is None:
  1393. for arch in self.all_arch_list:
  1394. if not os.path.exists(os.path.join(self.deploy_dir, arch)):
  1395. continue
  1396. arch_list.append(arch)
  1397. else:
  1398. arch_list = feed_archs.split()
  1399. feed_uris = self.construct_uris(feed_uris.split(), feed_base_paths.split())
  1400. with open(sources_conf, "w+") as sources_file:
  1401. for uri in feed_uris:
  1402. if arch_list:
  1403. for arch in arch_list:
  1404. bb.note('Adding dpkg channel at (%s)' % uri)
  1405. sources_file.write("deb %s/%s ./\n" %
  1406. (uri, arch))
  1407. else:
  1408. bb.note('Adding dpkg channel at (%s)' % uri)
  1409. sources_file.write("deb %s ./\n" % uri)
  1410. def _create_configs(self, archs, base_archs):
  1411. base_archs = re.sub(r"_", r"-", base_archs)
  1412. if os.path.exists(self.apt_conf_dir):
  1413. bb.utils.remove(self.apt_conf_dir, True)
  1414. bb.utils.mkdirhier(self.apt_conf_dir)
  1415. bb.utils.mkdirhier(self.apt_conf_dir + "/lists/partial/")
  1416. bb.utils.mkdirhier(self.apt_conf_dir + "/apt.conf.d/")
  1417. bb.utils.mkdirhier(self.apt_conf_dir + "/preferences.d/")
  1418. arch_list = []
  1419. for arch in self.all_arch_list:
  1420. if not os.path.exists(os.path.join(self.deploy_dir, arch)):
  1421. continue
  1422. arch_list.append(arch)
  1423. with open(os.path.join(self.apt_conf_dir, "preferences"), "w+") as prefs_file:
  1424. priority = 801
  1425. for arch in arch_list:
  1426. prefs_file.write(
  1427. "Package: *\n"
  1428. "Pin: release l=%s\n"
  1429. "Pin-Priority: %d\n\n" % (arch, priority))
  1430. priority += 5
  1431. pkg_exclude = self.d.getVar('PACKAGE_EXCLUDE') or ""
  1432. for pkg in pkg_exclude.split():
  1433. prefs_file.write(
  1434. "Package: %s\n"
  1435. "Pin: release *\n"
  1436. "Pin-Priority: -1\n\n" % pkg)
  1437. arch_list.reverse()
  1438. with open(os.path.join(self.apt_conf_dir, "sources.list"), "w+") as sources_file:
  1439. for arch in arch_list:
  1440. sources_file.write("deb file:%s/ ./\n" %
  1441. os.path.join(self.deploy_dir, arch))
  1442. base_arch_list = base_archs.split()
  1443. multilib_variants = self.d.getVar("MULTILIB_VARIANTS");
  1444. for variant in multilib_variants.split():
  1445. localdata = bb.data.createCopy(self.d)
  1446. variant_tune = localdata.getVar("DEFAULTTUNE_virtclass-multilib-" + variant, False)
  1447. orig_arch = localdata.getVar("DPKG_ARCH")
  1448. localdata.setVar("DEFAULTTUNE", variant_tune)
  1449. variant_arch = localdata.getVar("DPKG_ARCH")
  1450. if variant_arch not in base_arch_list:
  1451. base_arch_list.append(variant_arch)
  1452. with open(self.apt_conf_file, "w+") as apt_conf:
  1453. with open(self.d.expand("${STAGING_ETCDIR_NATIVE}/apt/apt.conf.sample")) as apt_conf_sample:
  1454. for line in apt_conf_sample.read().split("\n"):
  1455. match_arch = re.match(r" Architecture \".*\";$", line)
  1456. architectures = ""
  1457. if match_arch:
  1458. for base_arch in base_arch_list:
  1459. architectures += "\"%s\";" % base_arch
  1460. apt_conf.write(" Architectures {%s};\n" % architectures);
  1461. apt_conf.write(" Architecture \"%s\";\n" % base_archs)
  1462. else:
  1463. line = re.sub(r"#ROOTFS#", self.target_rootfs, line)
  1464. line = re.sub(r"#APTCONF#", self.apt_conf_dir, line)
  1465. apt_conf.write(line + "\n")
  1466. target_dpkg_dir = "%s/var/lib/dpkg" % self.target_rootfs
  1467. bb.utils.mkdirhier(os.path.join(target_dpkg_dir, "info"))
  1468. bb.utils.mkdirhier(os.path.join(target_dpkg_dir, "updates"))
  1469. if not os.path.exists(os.path.join(target_dpkg_dir, "status")):
  1470. open(os.path.join(target_dpkg_dir, "status"), "w+").close()
  1471. if not os.path.exists(os.path.join(target_dpkg_dir, "available")):
  1472. open(os.path.join(target_dpkg_dir, "available"), "w+").close()
  1473. def remove_packaging_data(self):
  1474. bb.utils.remove(os.path.join(self.target_rootfs,
  1475. self.d.getVar('opkglibdir')), True)
  1476. bb.utils.remove(self.target_rootfs + "/var/lib/dpkg/", True)
  1477. def fix_broken_dependencies(self):
  1478. os.environ['APT_CONFIG'] = self.apt_conf_file
  1479. cmd = "%s %s -f install" % (self.apt_get_cmd, self.apt_args)
  1480. try:
  1481. subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT)
  1482. except subprocess.CalledProcessError as e:
  1483. bb.fatal("Cannot fix broken dependencies. Command '%s' "
  1484. "returned %d:\n%s" % (cmd, e.returncode, e.output.decode("utf-8")))
  1485. def list_installed(self):
  1486. return DpkgPkgsList(self.d, self.target_rootfs).list_pkgs()
  1487. def package_info(self, pkg):
  1488. """
  1489. Returns a dictionary with the package info.
  1490. """
  1491. cmd = "%s show %s" % (self.apt_cache_cmd, pkg)
  1492. pkg_info = super(DpkgPM, self).package_info(pkg, cmd)
  1493. pkg_arch = pkg_info[pkg]["pkgarch"]
  1494. pkg_filename = pkg_info[pkg]["filename"]
  1495. pkg_info[pkg]["filepath"] = \
  1496. os.path.join(self.deploy_dir, pkg_arch, pkg_filename)
  1497. return pkg_info
  1498. def extract(self, pkg):
  1499. """
  1500. Returns the path to a tmpdir where resides the contents of a package.
  1501. Deleting the tmpdir is responsability of the caller.
  1502. """
  1503. pkg_info = self.package_info(pkg)
  1504. if not pkg_info:
  1505. bb.fatal("Unable to get information for package '%s' while "
  1506. "trying to extract the package." % pkg)
  1507. tmp_dir = super(DpkgPM, self).extract(pkg, pkg_info)
  1508. bb.utils.remove(os.path.join(tmp_dir, "data.tar.xz"))
  1509. return tmp_dir
  1510. def generate_index_files(d):
  1511. classes = d.getVar('PACKAGE_CLASSES').replace("package_", "").split()
  1512. indexer_map = {
  1513. "rpm": (RpmSubdirIndexer, d.getVar('DEPLOY_DIR_RPM')),
  1514. "ipk": (OpkgIndexer, d.getVar('DEPLOY_DIR_IPK')),
  1515. "deb": (DpkgIndexer, d.getVar('DEPLOY_DIR_DEB'))
  1516. }
  1517. result = None
  1518. for pkg_class in classes:
  1519. if not pkg_class in indexer_map:
  1520. continue
  1521. if os.path.exists(indexer_map[pkg_class][1]):
  1522. result = indexer_map[pkg_class][0](d, indexer_map[pkg_class][1]).write_index()
  1523. if result is not None:
  1524. bb.fatal(result)