package_manager.py 79 KB

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