package_manager.py 79 KB

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