wic.py 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544
  1. #
  2. # Copyright (c) 2015, Intel Corporation.
  3. #
  4. # SPDX-License-Identifier: GPL-2.0-only
  5. #
  6. # AUTHORS
  7. # Ed Bartosh <ed.bartosh@linux.intel.com>
  8. """Test cases for wic."""
  9. import os
  10. import sys
  11. import unittest
  12. import hashlib
  13. from glob import glob
  14. from shutil import rmtree, copy
  15. from tempfile import NamedTemporaryFile
  16. from oeqa.selftest.case import OESelftestTestCase
  17. from oeqa.core.decorator import OETestTag
  18. from oeqa.core.decorator.data import skipIfNotArch
  19. from oeqa.utils.commands import runCmd, bitbake, get_bb_var, get_bb_vars, runqemu
  20. def extract_files(debugfs_output):
  21. """
  22. extract file names from the output of debugfs -R 'ls -p',
  23. which looks like this:
  24. /2/040755/0/0/.//\n
  25. /2/040755/0/0/..//\n
  26. /11/040700/0/0/lost+found^M//\n
  27. /12/040755/1002/1002/run//\n
  28. /13/040755/1002/1002/sys//\n
  29. /14/040755/1002/1002/bin//\n
  30. /80/040755/1002/1002/var//\n
  31. /92/040755/1002/1002/tmp//\n
  32. """
  33. # NOTE the occasional ^M in file names
  34. return [line.split('/')[5].strip() for line in \
  35. debugfs_output.strip().split('/\n')]
  36. def files_own_by_root(debugfs_output):
  37. for line in debugfs_output.strip().split('/\n'):
  38. if line.split('/')[3:5] != ['0', '0']:
  39. print(debugfs_output)
  40. return False
  41. return True
  42. class WicTestCase(OESelftestTestCase):
  43. """Wic test class."""
  44. image_is_ready = False
  45. wicenv_cache = {}
  46. def setUpLocal(self):
  47. """This code is executed before each test method."""
  48. self.resultdir = os.path.join(self.builddir, "wic-tmp")
  49. super(WicTestCase, self).setUpLocal()
  50. # Do this here instead of in setUpClass as the base setUp does some
  51. # clean up which can result in the native tools built earlier in
  52. # setUpClass being unavailable.
  53. if not WicTestCase.image_is_ready:
  54. if self.td['USE_NLS'] != 'yes':
  55. self.skipTest('wic-tools needs USE_NLS=yes')
  56. bitbake('wic-tools core-image-minimal core-image-minimal-mtdutils')
  57. WicTestCase.image_is_ready = True
  58. rmtree(self.resultdir, ignore_errors=True)
  59. def tearDownLocal(self):
  60. """Remove resultdir as it may contain images."""
  61. rmtree(self.resultdir, ignore_errors=True)
  62. super(WicTestCase, self).tearDownLocal()
  63. def _get_image_env_path(self, image):
  64. """Generate and obtain the path to <image>.env"""
  65. if image not in WicTestCase.wicenv_cache:
  66. bitbake('%s -c do_rootfs_wicenv' % image)
  67. stdir = get_bb_var('STAGING_DIR', image)
  68. machine = self.td["MACHINE"]
  69. WicTestCase.wicenv_cache[image] = os.path.join(stdir, machine, 'imgdata')
  70. return WicTestCase.wicenv_cache[image]
  71. class CLITests(OESelftestTestCase):
  72. def test_version(self):
  73. """Test wic --version"""
  74. runCmd('wic --version')
  75. def test_help(self):
  76. """Test wic --help and wic -h"""
  77. runCmd('wic --help')
  78. runCmd('wic -h')
  79. def test_createhelp(self):
  80. """Test wic create --help"""
  81. runCmd('wic create --help')
  82. def test_listhelp(self):
  83. """Test wic list --help"""
  84. runCmd('wic list --help')
  85. def test_help_create(self):
  86. """Test wic help create"""
  87. runCmd('wic help create')
  88. def test_help_list(self):
  89. """Test wic help list"""
  90. runCmd('wic help list')
  91. def test_help_overview(self):
  92. """Test wic help overview"""
  93. runCmd('wic help overview')
  94. def test_help_plugins(self):
  95. """Test wic help plugins"""
  96. runCmd('wic help plugins')
  97. def test_help_kickstart(self):
  98. """Test wic help kickstart"""
  99. runCmd('wic help kickstart')
  100. def test_list_images(self):
  101. """Test wic list images"""
  102. runCmd('wic list images')
  103. def test_list_source_plugins(self):
  104. """Test wic list source-plugins"""
  105. runCmd('wic list source-plugins')
  106. def test_listed_images_help(self):
  107. """Test wic listed images help"""
  108. output = runCmd('wic list images').output
  109. imagelist = [line.split()[0] for line in output.splitlines()]
  110. for image in imagelist:
  111. runCmd('wic list %s help' % image)
  112. def test_unsupported_subcommand(self):
  113. """Test unsupported subcommand"""
  114. self.assertNotEqual(0, runCmd('wic unsupported', ignore_status=True).status)
  115. def test_no_command(self):
  116. """Test wic without command"""
  117. self.assertEqual(1, runCmd('wic', ignore_status=True).status)
  118. class Wic(WicTestCase):
  119. def test_build_image_name(self):
  120. """Test wic create wictestdisk --image-name=core-image-minimal"""
  121. cmd = "wic create wictestdisk --image-name=core-image-minimal -o %s" % self.resultdir
  122. runCmd(cmd)
  123. self.assertEqual(1, len(glob(os.path.join (self.resultdir, "wictestdisk-*.direct"))))
  124. @skipIfNotArch(['i586', 'i686', 'x86_64'])
  125. def test_gpt_image(self):
  126. """Test creation of core-image-minimal with gpt table and UUID boot"""
  127. cmd = "wic create directdisk-gpt --image-name core-image-minimal -o %s" % self.resultdir
  128. runCmd(cmd)
  129. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "directdisk-*.direct"))))
  130. @skipIfNotArch(['i586', 'i686', 'x86_64'])
  131. def test_iso_image(self):
  132. """Test creation of hybrid iso image with legacy and EFI boot"""
  133. config = 'INITRAMFS_IMAGE = "core-image-minimal-initramfs"\n'\
  134. 'MACHINE_FEATURES:append = " efi"\n'\
  135. 'DEPENDS:pn-core-image-minimal += "syslinux"\n'
  136. self.append_config(config)
  137. bitbake('core-image-minimal core-image-minimal-initramfs')
  138. self.remove_config(config)
  139. cmd = "wic create mkhybridiso --image-name core-image-minimal -o %s" % self.resultdir
  140. runCmd(cmd)
  141. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "HYBRID_ISO_IMG-*.direct"))))
  142. self.assertEqual(1, len(glob(os.path.join (self.resultdir, "HYBRID_ISO_IMG-*.iso"))))
  143. @skipIfNotArch(['i586', 'i686', 'x86_64'])
  144. def test_qemux86_directdisk(self):
  145. """Test creation of qemux-86-directdisk image"""
  146. cmd = "wic create qemux86-directdisk -e core-image-minimal -o %s" % self.resultdir
  147. runCmd(cmd)
  148. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "qemux86-directdisk-*direct"))))
  149. @skipIfNotArch(['i586', 'i686', 'x86_64', 'aarch64'])
  150. def test_mkefidisk(self):
  151. """Test creation of mkefidisk image"""
  152. cmd = "wic create mkefidisk -e core-image-minimal -o %s" % self.resultdir
  153. runCmd(cmd)
  154. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "mkefidisk-*direct"))))
  155. @skipIfNotArch(['i586', 'i686', 'x86_64'])
  156. def test_bootloader_config(self):
  157. """Test creation of directdisk-bootloader-config image"""
  158. config = 'DEPENDS:pn-core-image-minimal += "syslinux"\n'
  159. self.append_config(config)
  160. bitbake('core-image-minimal')
  161. self.remove_config(config)
  162. cmd = "wic create directdisk-bootloader-config -e core-image-minimal -o %s" % self.resultdir
  163. runCmd(cmd)
  164. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "directdisk-bootloader-config-*direct"))))
  165. @skipIfNotArch(['i586', 'i686', 'x86_64', 'aarch64'])
  166. def test_systemd_bootdisk(self):
  167. """Test creation of systemd-bootdisk image"""
  168. config = 'MACHINE_FEATURES:append = " efi"\n'
  169. self.append_config(config)
  170. bitbake('core-image-minimal')
  171. self.remove_config(config)
  172. cmd = "wic create systemd-bootdisk -e core-image-minimal -o %s" % self.resultdir
  173. runCmd(cmd)
  174. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "systemd-bootdisk-*direct"))))
  175. def test_efi_bootpart(self):
  176. """Test creation of efi-bootpart image"""
  177. cmd = "wic create mkefidisk -e core-image-minimal -o %s" % self.resultdir
  178. kimgtype = get_bb_var('KERNEL_IMAGETYPE', 'core-image-minimal')
  179. self.append_config('IMAGE_EFI_BOOT_FILES = "%s;kernel"\n' % kimgtype)
  180. runCmd(cmd)
  181. sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
  182. images = glob(os.path.join(self.resultdir, "mkefidisk-*.direct"))
  183. result = runCmd("wic ls %s:1/ -n %s" % (images[0], sysroot))
  184. self.assertIn("kernel",result.output)
  185. def test_sdimage_bootpart(self):
  186. """Test creation of sdimage-bootpart image"""
  187. cmd = "wic create sdimage-bootpart -e core-image-minimal -o %s" % self.resultdir
  188. kimgtype = get_bb_var('KERNEL_IMAGETYPE', 'core-image-minimal')
  189. self.write_config('IMAGE_BOOT_FILES = "%s"\n' % kimgtype)
  190. runCmd(cmd)
  191. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "sdimage-bootpart-*direct"))))
  192. # TODO this doesn't have to be x86-specific
  193. @skipIfNotArch(['i586', 'i686', 'x86_64'])
  194. def test_default_output_dir(self):
  195. """Test default output location"""
  196. for fname in glob("directdisk-*.direct"):
  197. os.remove(fname)
  198. config = 'DEPENDS:pn-core-image-minimal += "syslinux"\n'
  199. self.append_config(config)
  200. bitbake('core-image-minimal')
  201. self.remove_config(config)
  202. cmd = "wic create directdisk -e core-image-minimal"
  203. runCmd(cmd)
  204. self.assertEqual(1, len(glob("directdisk-*.direct")))
  205. @skipIfNotArch(['i586', 'i686', 'x86_64'])
  206. def test_build_artifacts(self):
  207. """Test wic create directdisk providing all artifacts."""
  208. bb_vars = get_bb_vars(['STAGING_DATADIR', 'RECIPE_SYSROOT_NATIVE'],
  209. 'wic-tools')
  210. bb_vars.update(get_bb_vars(['DEPLOY_DIR_IMAGE', 'IMAGE_ROOTFS'],
  211. 'core-image-minimal'))
  212. bbvars = {key.lower(): value for key, value in bb_vars.items()}
  213. bbvars['resultdir'] = self.resultdir
  214. runCmd("wic create directdisk "
  215. "-b %(staging_datadir)s "
  216. "-k %(deploy_dir_image)s "
  217. "-n %(recipe_sysroot_native)s "
  218. "-r %(image_rootfs)s "
  219. "-o %(resultdir)s" % bbvars)
  220. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "directdisk-*.direct"))))
  221. def test_compress_gzip(self):
  222. """Test compressing an image with gzip"""
  223. runCmd("wic create wictestdisk "
  224. "--image-name core-image-minimal "
  225. "-c gzip -o %s" % self.resultdir)
  226. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "wictestdisk-*.direct.gz"))))
  227. def test_compress_bzip2(self):
  228. """Test compressing an image with bzip2"""
  229. runCmd("wic create wictestdisk "
  230. "--image-name=core-image-minimal "
  231. "-c bzip2 -o %s" % self.resultdir)
  232. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "wictestdisk-*.direct.bz2"))))
  233. def test_compress_xz(self):
  234. """Test compressing an image with xz"""
  235. runCmd("wic create wictestdisk "
  236. "--image-name=core-image-minimal "
  237. "--compress-with=xz -o %s" % self.resultdir)
  238. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "wictestdisk-*.direct.xz"))))
  239. def test_wrong_compressor(self):
  240. """Test how wic breaks if wrong compressor is provided"""
  241. self.assertEqual(2, runCmd("wic create wictestdisk "
  242. "--image-name=core-image-minimal "
  243. "-c wrong -o %s" % self.resultdir,
  244. ignore_status=True).status)
  245. def test_debug_short(self):
  246. """Test -D option"""
  247. runCmd("wic create wictestdisk "
  248. "--image-name=core-image-minimal "
  249. "-D -o %s" % self.resultdir)
  250. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "wictestdisk-*.direct"))))
  251. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "tmp.wic*"))))
  252. def test_debug_long(self):
  253. """Test --debug option"""
  254. runCmd("wic create wictestdisk "
  255. "--image-name=core-image-minimal "
  256. "--debug -o %s" % self.resultdir)
  257. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "wictestdisk-*.direct"))))
  258. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "tmp.wic*"))))
  259. def test_skip_build_check_short(self):
  260. """Test -s option"""
  261. runCmd("wic create wictestdisk "
  262. "--image-name=core-image-minimal "
  263. "-s -o %s" % self.resultdir)
  264. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "wictestdisk-*.direct"))))
  265. def test_skip_build_check_long(self):
  266. """Test --skip-build-check option"""
  267. runCmd("wic create wictestdisk "
  268. "--image-name=core-image-minimal "
  269. "--skip-build-check "
  270. "--outdir %s" % self.resultdir)
  271. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "wictestdisk-*.direct"))))
  272. def test_build_rootfs_short(self):
  273. """Test -f option"""
  274. runCmd("wic create wictestdisk "
  275. "--image-name=core-image-minimal "
  276. "-f -o %s" % self.resultdir)
  277. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "wictestdisk-*.direct"))))
  278. def test_build_rootfs_long(self):
  279. """Test --build-rootfs option"""
  280. runCmd("wic create wictestdisk "
  281. "--image-name=core-image-minimal "
  282. "--build-rootfs "
  283. "--outdir %s" % self.resultdir)
  284. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "wictestdisk-*.direct"))))
  285. # TODO this doesn't have to be x86-specific
  286. @skipIfNotArch(['i586', 'i686', 'x86_64'])
  287. def test_rootfs_indirect_recipes(self):
  288. """Test usage of rootfs plugin with rootfs recipes"""
  289. runCmd("wic create directdisk-multi-rootfs "
  290. "--image-name=core-image-minimal "
  291. "--rootfs rootfs1=core-image-minimal "
  292. "--rootfs rootfs2=core-image-minimal "
  293. "--outdir %s" % self.resultdir)
  294. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "directdisk-multi-rootfs*.direct"))))
  295. # TODO this doesn't have to be x86-specific
  296. @skipIfNotArch(['i586', 'i686', 'x86_64'])
  297. def test_rootfs_artifacts(self):
  298. """Test usage of rootfs plugin with rootfs paths"""
  299. bb_vars = get_bb_vars(['STAGING_DATADIR', 'RECIPE_SYSROOT_NATIVE'],
  300. 'wic-tools')
  301. bb_vars.update(get_bb_vars(['DEPLOY_DIR_IMAGE', 'IMAGE_ROOTFS'],
  302. 'core-image-minimal'))
  303. bbvars = {key.lower(): value for key, value in bb_vars.items()}
  304. bbvars['wks'] = "directdisk-multi-rootfs"
  305. bbvars['resultdir'] = self.resultdir
  306. runCmd("wic create %(wks)s "
  307. "--bootimg-dir=%(staging_datadir)s "
  308. "--kernel-dir=%(deploy_dir_image)s "
  309. "--native-sysroot=%(recipe_sysroot_native)s "
  310. "--rootfs-dir rootfs1=%(image_rootfs)s "
  311. "--rootfs-dir rootfs2=%(image_rootfs)s "
  312. "--outdir %(resultdir)s" % bbvars)
  313. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "%(wks)s-*.direct" % bbvars))))
  314. def test_exclude_path(self):
  315. """Test --exclude-path wks option."""
  316. oldpath = os.environ['PATH']
  317. os.environ['PATH'] = get_bb_var("PATH", "wic-tools")
  318. try:
  319. wks_file = 'temp.wks'
  320. with open(wks_file, 'w') as wks:
  321. rootfs_dir = get_bb_var('IMAGE_ROOTFS', 'core-image-minimal')
  322. wks.write("""
  323. part / --source rootfs --ondisk mmcblk0 --fstype=ext4 --exclude-path usr
  324. part /usr --source rootfs --ondisk mmcblk0 --fstype=ext4 --rootfs-dir %s/usr
  325. part /etc --source rootfs --ondisk mmcblk0 --fstype=ext4 --exclude-path bin/ --rootfs-dir %s/usr"""
  326. % (rootfs_dir, rootfs_dir))
  327. runCmd("wic create %s -e core-image-minimal -o %s" \
  328. % (wks_file, self.resultdir))
  329. os.remove(wks_file)
  330. wicout = glob(os.path.join(self.resultdir, "%s-*direct" % 'temp'))
  331. self.assertEqual(1, len(wicout))
  332. wicimg = wicout[0]
  333. # verify partition size with wic
  334. res = runCmd("parted -m %s unit b p 2>/dev/null" % wicimg)
  335. # parse parted output which looks like this:
  336. # BYT;\n
  337. # /var/tmp/wic/build/tmpfwvjjkf_-201611101222-hda.direct:200MiB:file:512:512:msdos::;\n
  338. # 1:0.00MiB:200MiB:200MiB:ext4::;\n
  339. partlns = res.output.splitlines()[2:]
  340. self.assertEqual(3, len(partlns))
  341. for part in [1, 2, 3]:
  342. part_file = os.path.join(self.resultdir, "selftest_img.part%d" % part)
  343. partln = partlns[part-1].split(":")
  344. self.assertEqual(7, len(partln))
  345. start = int(partln[1].rstrip("B")) / 512
  346. length = int(partln[3].rstrip("B")) / 512
  347. runCmd("dd if=%s of=%s skip=%d count=%d" %
  348. (wicimg, part_file, start, length))
  349. # Test partition 1, should contain the normal root directories, except
  350. # /usr.
  351. res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % \
  352. os.path.join(self.resultdir, "selftest_img.part1"))
  353. files = extract_files(res.output)
  354. self.assertIn("etc", files)
  355. self.assertNotIn("usr", files)
  356. # Partition 2, should contain common directories for /usr, not root
  357. # directories.
  358. res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % \
  359. os.path.join(self.resultdir, "selftest_img.part2"))
  360. files = extract_files(res.output)
  361. self.assertNotIn("etc", files)
  362. self.assertNotIn("usr", files)
  363. self.assertIn("share", files)
  364. # Partition 3, should contain the same as partition 2, including the bin
  365. # directory, but not the files inside it.
  366. res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % \
  367. os.path.join(self.resultdir, "selftest_img.part3"))
  368. files = extract_files(res.output)
  369. self.assertNotIn("etc", files)
  370. self.assertNotIn("usr", files)
  371. self.assertIn("share", files)
  372. self.assertIn("bin", files)
  373. res = runCmd("debugfs -R 'ls -p bin' %s 2>/dev/null" % \
  374. os.path.join(self.resultdir, "selftest_img.part3"))
  375. files = extract_files(res.output)
  376. self.assertIn(".", files)
  377. self.assertIn("..", files)
  378. self.assertEqual(2, len(files))
  379. for part in [1, 2, 3]:
  380. part_file = os.path.join(self.resultdir, "selftest_img.part%d" % part)
  381. os.remove(part_file)
  382. finally:
  383. os.environ['PATH'] = oldpath
  384. def test_include_path(self):
  385. """Test --include-path wks option."""
  386. oldpath = os.environ['PATH']
  387. os.environ['PATH'] = get_bb_var("PATH", "wic-tools")
  388. try:
  389. include_path = os.path.join(self.resultdir, 'test-include')
  390. os.makedirs(include_path)
  391. with open(os.path.join(include_path, 'test-file'), 'w') as t:
  392. t.write("test\n")
  393. wks_file = os.path.join(include_path, 'temp.wks')
  394. with open(wks_file, 'w') as wks:
  395. rootfs_dir = get_bb_var('IMAGE_ROOTFS', 'core-image-minimal')
  396. wks.write("""
  397. part /part1 --source rootfs --ondisk mmcblk0 --fstype=ext4
  398. part /part2 --source rootfs --ondisk mmcblk0 --fstype=ext4 --include-path %s"""
  399. % (include_path))
  400. runCmd("wic create %s -e core-image-minimal -o %s" \
  401. % (wks_file, self.resultdir))
  402. part1 = glob(os.path.join(self.resultdir, 'temp-*.direct.p1'))[0]
  403. part2 = glob(os.path.join(self.resultdir, 'temp-*.direct.p2'))[0]
  404. # Test partition 1, should not contain 'test-file'
  405. res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % (part1))
  406. files = extract_files(res.output)
  407. self.assertNotIn('test-file', files)
  408. self.assertEqual(True, files_own_by_root(res.output))
  409. # Test partition 2, should contain 'test-file'
  410. res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % (part2))
  411. files = extract_files(res.output)
  412. self.assertIn('test-file', files)
  413. self.assertEqual(True, files_own_by_root(res.output))
  414. finally:
  415. os.environ['PATH'] = oldpath
  416. def test_include_path_embeded(self):
  417. """Test --include-path wks option."""
  418. oldpath = os.environ['PATH']
  419. os.environ['PATH'] = get_bb_var("PATH", "wic-tools")
  420. try:
  421. include_path = os.path.join(self.resultdir, 'test-include')
  422. os.makedirs(include_path)
  423. with open(os.path.join(include_path, 'test-file'), 'w') as t:
  424. t.write("test\n")
  425. wks_file = os.path.join(include_path, 'temp.wks')
  426. with open(wks_file, 'w') as wks:
  427. wks.write("""
  428. part / --source rootfs --fstype=ext4 --include-path %s --include-path core-image-minimal-mtdutils export/"""
  429. % (include_path))
  430. runCmd("wic create %s -e core-image-minimal -o %s" \
  431. % (wks_file, self.resultdir))
  432. part1 = glob(os.path.join(self.resultdir, 'temp-*.direct.p1'))[0]
  433. res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % (part1))
  434. files = extract_files(res.output)
  435. self.assertIn('test-file', files)
  436. self.assertEqual(True, files_own_by_root(res.output))
  437. res = runCmd("debugfs -R 'ls -p /export/etc/' %s 2>/dev/null" % (part1))
  438. files = extract_files(res.output)
  439. self.assertIn('passwd', files)
  440. self.assertEqual(True, files_own_by_root(res.output))
  441. finally:
  442. os.environ['PATH'] = oldpath
  443. def test_include_path_errors(self):
  444. """Test --include-path wks option error handling."""
  445. wks_file = 'temp.wks'
  446. # Absolute argument.
  447. with open(wks_file, 'w') as wks:
  448. wks.write("part / --source rootfs --fstype=ext4 --include-path core-image-minimal-mtdutils /export")
  449. self.assertNotEqual(0, runCmd("wic create %s -e core-image-minimal -o %s" \
  450. % (wks_file, self.resultdir), ignore_status=True).status)
  451. os.remove(wks_file)
  452. # Argument pointing to parent directory.
  453. with open(wks_file, 'w') as wks:
  454. wks.write("part / --source rootfs --fstype=ext4 --include-path core-image-minimal-mtdutils ././..")
  455. self.assertNotEqual(0, runCmd("wic create %s -e core-image-minimal -o %s" \
  456. % (wks_file, self.resultdir), ignore_status=True).status)
  457. os.remove(wks_file)
  458. # 3 Argument pointing to parent directory.
  459. with open(wks_file, 'w') as wks:
  460. wks.write("part / --source rootfs --fstype=ext4 --include-path core-image-minimal-mtdutils export/ dummy")
  461. self.assertNotEqual(0, runCmd("wic create %s -e core-image-minimal -o %s" \
  462. % (wks_file, self.resultdir), ignore_status=True).status)
  463. os.remove(wks_file)
  464. def test_exclude_path_errors(self):
  465. """Test --exclude-path wks option error handling."""
  466. wks_file = 'temp.wks'
  467. # Absolute argument.
  468. with open(wks_file, 'w') as wks:
  469. wks.write("part / --source rootfs --ondisk mmcblk0 --fstype=ext4 --exclude-path /usr")
  470. self.assertNotEqual(0, runCmd("wic create %s -e core-image-minimal -o %s" \
  471. % (wks_file, self.resultdir), ignore_status=True).status)
  472. os.remove(wks_file)
  473. # Argument pointing to parent directory.
  474. with open(wks_file, 'w') as wks:
  475. wks.write("part / --source rootfs --ondisk mmcblk0 --fstype=ext4 --exclude-path ././..")
  476. self.assertNotEqual(0, runCmd("wic create %s -e core-image-minimal -o %s" \
  477. % (wks_file, self.resultdir), ignore_status=True).status)
  478. os.remove(wks_file)
  479. def test_permissions(self):
  480. """Test permissions are respected"""
  481. # prepare wicenv and rootfs
  482. bitbake('core-image-minimal core-image-minimal-mtdutils -c do_rootfs_wicenv')
  483. oldpath = os.environ['PATH']
  484. os.environ['PATH'] = get_bb_var("PATH", "wic-tools")
  485. t_normal = """
  486. part / --source rootfs --fstype=ext4
  487. """
  488. t_exclude = """
  489. part / --source rootfs --fstype=ext4 --exclude-path=home
  490. """
  491. t_multi = """
  492. part / --source rootfs --ondisk sda --fstype=ext4
  493. part /export --source rootfs --rootfs=core-image-minimal-mtdutils --fstype=ext4
  494. """
  495. t_change = """
  496. part / --source rootfs --ondisk sda --fstype=ext4 --exclude-path=etc/   
  497. part /etc --source rootfs --fstype=ext4 --change-directory=etc
  498. """
  499. tests = [t_normal, t_exclude, t_multi, t_change]
  500. try:
  501. for test in tests:
  502. include_path = os.path.join(self.resultdir, 'test-include')
  503. os.makedirs(include_path)
  504. wks_file = os.path.join(include_path, 'temp.wks')
  505. with open(wks_file, 'w') as wks:
  506. wks.write(test)
  507. runCmd("wic create %s -e core-image-minimal -o %s" \
  508. % (wks_file, self.resultdir))
  509. for part in glob(os.path.join(self.resultdir, 'temp-*.direct.p*')):
  510. res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % (part))
  511. self.assertEqual(True, files_own_by_root(res.output))
  512. config = 'IMAGE_FSTYPES += "wic"\nWKS_FILE = "%s"\n' % wks_file
  513. self.append_config(config)
  514. bitbake('core-image-minimal')
  515. tmpdir = os.path.join(get_bb_var('WORKDIR', 'core-image-minimal'),'build-wic')
  516. # check each partition for permission
  517. for part in glob(os.path.join(tmpdir, 'temp-*.direct.p*')):
  518. res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % (part))
  519. self.assertTrue(files_own_by_root(res.output)
  520. ,msg='Files permission incorrect using wks set "%s"' % test)
  521. # clean config and result directory for next cases
  522. self.remove_config(config)
  523. rmtree(self.resultdir, ignore_errors=True)
  524. finally:
  525. os.environ['PATH'] = oldpath
  526. def test_change_directory(self):
  527. """Test --change-directory wks option."""
  528. oldpath = os.environ['PATH']
  529. os.environ['PATH'] = get_bb_var("PATH", "wic-tools")
  530. try:
  531. include_path = os.path.join(self.resultdir, 'test-include')
  532. os.makedirs(include_path)
  533. wks_file = os.path.join(include_path, 'temp.wks')
  534. with open(wks_file, 'w') as wks:
  535. wks.write("part /etc --source rootfs --fstype=ext4 --change-directory=etc")
  536. runCmd("wic create %s -e core-image-minimal -o %s" \
  537. % (wks_file, self.resultdir))
  538. part1 = glob(os.path.join(self.resultdir, 'temp-*.direct.p1'))[0]
  539. res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % (part1))
  540. files = extract_files(res.output)
  541. self.assertIn('passwd', files)
  542. finally:
  543. os.environ['PATH'] = oldpath
  544. def test_change_directory_errors(self):
  545. """Test --change-directory wks option error handling."""
  546. wks_file = 'temp.wks'
  547. # Absolute argument.
  548. with open(wks_file, 'w') as wks:
  549. wks.write("part / --source rootfs --fstype=ext4 --change-directory /usr")
  550. self.assertNotEqual(0, runCmd("wic create %s -e core-image-minimal -o %s" \
  551. % (wks_file, self.resultdir), ignore_status=True).status)
  552. os.remove(wks_file)
  553. # Argument pointing to parent directory.
  554. with open(wks_file, 'w') as wks:
  555. wks.write("part / --source rootfs --fstype=ext4 --change-directory ././..")
  556. self.assertNotEqual(0, runCmd("wic create %s -e core-image-minimal -o %s" \
  557. % (wks_file, self.resultdir), ignore_status=True).status)
  558. os.remove(wks_file)
  559. def test_no_fstab_update(self):
  560. """Test --no-fstab-update wks option."""
  561. oldpath = os.environ['PATH']
  562. os.environ['PATH'] = get_bb_var("PATH", "wic-tools")
  563. # Get stock fstab from base-files recipe
  564. bitbake('base-files -c do_install')
  565. bf_fstab = os.path.join(get_bb_var('D', 'base-files'), 'etc', 'fstab')
  566. self.assertEqual(True, os.path.exists(bf_fstab))
  567. bf_fstab_md5sum = runCmd('md5sum %s 2>/dev/null' % bf_fstab).output.split(" ")[0]
  568. try:
  569. no_fstab_update_path = os.path.join(self.resultdir, 'test-no-fstab-update')
  570. os.makedirs(no_fstab_update_path)
  571. wks_file = os.path.join(no_fstab_update_path, 'temp.wks')
  572. with open(wks_file, 'w') as wks:
  573. wks.writelines(['part / --source rootfs --fstype=ext4 --label rootfs\n',
  574. 'part /mnt/p2 --source rootfs --rootfs-dir=core-image-minimal ',
  575. '--fstype=ext4 --label p2 --no-fstab-update\n'])
  576. runCmd("wic create %s -e core-image-minimal -o %s" \
  577. % (wks_file, self.resultdir))
  578. part_fstab_md5sum = []
  579. for i in range(1, 3):
  580. part = glob(os.path.join(self.resultdir, 'temp-*.direct.p') + str(i))[0]
  581. part_fstab = runCmd("debugfs -R 'cat etc/fstab' %s 2>/dev/null" % (part))
  582. part_fstab_md5sum.append(hashlib.md5((part_fstab.output + "\n\n").encode('utf-8')).hexdigest())
  583. # '/etc/fstab' in partition 2 should contain the same stock fstab file
  584. # as the one installed by the base-file recipe.
  585. self.assertEqual(bf_fstab_md5sum, part_fstab_md5sum[1])
  586. # '/etc/fstab' in partition 1 should contain an updated fstab file.
  587. self.assertNotEqual(bf_fstab_md5sum, part_fstab_md5sum[0])
  588. finally:
  589. os.environ['PATH'] = oldpath
  590. def test_no_fstab_update_errors(self):
  591. """Test --no-fstab-update wks option error handling."""
  592. wks_file = 'temp.wks'
  593. # Absolute argument.
  594. with open(wks_file, 'w') as wks:
  595. wks.write("part / --source rootfs --fstype=ext4 --no-fstab-update /etc")
  596. self.assertNotEqual(0, runCmd("wic create %s -e core-image-minimal -o %s" \
  597. % (wks_file, self.resultdir), ignore_status=True).status)
  598. os.remove(wks_file)
  599. # Argument pointing to parent directory.
  600. with open(wks_file, 'w') as wks:
  601. wks.write("part / --source rootfs --fstype=ext4 --no-fstab-update ././..")
  602. self.assertNotEqual(0, runCmd("wic create %s -e core-image-minimal -o %s" \
  603. % (wks_file, self.resultdir), ignore_status=True).status)
  604. os.remove(wks_file)
  605. def test_extra_space(self):
  606. """Test --extra-space wks option."""
  607. extraspace = 1024**3
  608. runCmd("wic create wictestdisk "
  609. "--image-name core-image-minimal "
  610. "--extra-space %i -o %s" % (extraspace ,self.resultdir))
  611. wicout = glob(os.path.join(self.resultdir, "wictestdisk-*.direct"))
  612. self.assertEqual(1, len(wicout))
  613. size = os.path.getsize(wicout[0])
  614. self.assertTrue(size > extraspace)
  615. class Wic2(WicTestCase):
  616. def test_bmap_short(self):
  617. """Test generation of .bmap file -m option"""
  618. cmd = "wic create wictestdisk -e core-image-minimal -m -o %s" % self.resultdir
  619. runCmd(cmd)
  620. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "wictestdisk-*direct"))))
  621. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "wictestdisk-*direct.bmap"))))
  622. def test_bmap_long(self):
  623. """Test generation of .bmap file --bmap option"""
  624. cmd = "wic create wictestdisk -e core-image-minimal --bmap -o %s" % self.resultdir
  625. runCmd(cmd)
  626. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "wictestdisk-*direct"))))
  627. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "wictestdisk-*direct.bmap"))))
  628. def test_image_env(self):
  629. """Test generation of <image>.env files."""
  630. image = 'core-image-minimal'
  631. imgdatadir = self._get_image_env_path(image)
  632. bb_vars = get_bb_vars(['IMAGE_BASENAME', 'WICVARS'], image)
  633. basename = bb_vars['IMAGE_BASENAME']
  634. self.assertEqual(basename, image)
  635. path = os.path.join(imgdatadir, basename) + '.env'
  636. self.assertTrue(os.path.isfile(path))
  637. wicvars = set(bb_vars['WICVARS'].split())
  638. # filter out optional variables
  639. wicvars = wicvars.difference(('DEPLOY_DIR_IMAGE', 'IMAGE_BOOT_FILES',
  640. 'INITRD', 'INITRD_LIVE', 'ISODIR','INITRAMFS_IMAGE',
  641. 'INITRAMFS_IMAGE_BUNDLE', 'INITRAMFS_LINK_NAME',
  642. 'APPEND', 'IMAGE_EFI_BOOT_FILES'))
  643. with open(path) as envfile:
  644. content = dict(line.split("=", 1) for line in envfile)
  645. # test if variables used by wic present in the .env file
  646. for var in wicvars:
  647. self.assertTrue(var in content, "%s is not in .env file" % var)
  648. self.assertTrue(content[var])
  649. def test_image_vars_dir_short(self):
  650. """Test image vars directory selection -v option"""
  651. image = 'core-image-minimal'
  652. imgenvdir = self._get_image_env_path(image)
  653. native_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "wic-tools")
  654. runCmd("wic create wictestdisk "
  655. "--image-name=%s -v %s -n %s -o %s"
  656. % (image, imgenvdir, native_sysroot,
  657. self.resultdir))
  658. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "wictestdisk-*direct"))))
  659. def test_image_vars_dir_long(self):
  660. """Test image vars directory selection --vars option"""
  661. image = 'core-image-minimal'
  662. imgenvdir = self._get_image_env_path(image)
  663. native_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "wic-tools")
  664. runCmd("wic create wictestdisk "
  665. "--image-name=%s "
  666. "--vars %s "
  667. "--native-sysroot %s "
  668. "--outdir %s"
  669. % (image, imgenvdir, native_sysroot,
  670. self.resultdir))
  671. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "wictestdisk-*direct"))))
  672. # TODO this test could also work on aarch64
  673. @skipIfNotArch(['i586', 'i686', 'x86_64'])
  674. def test_wic_image_type(self):
  675. """Test building wic images by bitbake"""
  676. config = 'IMAGE_FSTYPES += "wic"\nWKS_FILE = "wic-image-minimal"\n'\
  677. 'MACHINE_FEATURES:append = " efi"\n'
  678. self.append_config(config)
  679. image = 'wic-image-minimal'
  680. bitbake(image)
  681. self.remove_config(config)
  682. bb_vars = get_bb_vars(['DEPLOY_DIR_IMAGE', 'IMAGE_LINK_NAME'], image)
  683. prefix = os.path.join(bb_vars['DEPLOY_DIR_IMAGE'], '%s.' % bb_vars['IMAGE_LINK_NAME'])
  684. # check if we have result image and manifests symlinks
  685. # pointing to existing files
  686. for suffix in ('wic', 'manifest'):
  687. path = prefix + suffix
  688. self.assertTrue(os.path.islink(path))
  689. self.assertTrue(os.path.isfile(os.path.realpath(path)))
  690. # TODO this should work on aarch64
  691. @skipIfNotArch(['i586', 'i686', 'x86_64'])
  692. @OETestTag("runqemu")
  693. def test_qemu(self):
  694. """Test wic-image-minimal under qemu"""
  695. config = 'IMAGE_FSTYPES += "wic"\nWKS_FILE = "wic-image-minimal"\n'\
  696. 'MACHINE_FEATURES:append = " efi"\n'
  697. self.append_config(config)
  698. bitbake('wic-image-minimal')
  699. self.remove_config(config)
  700. with runqemu('wic-image-minimal', ssh=False, runqemuparams='nographic') as qemu:
  701. cmd = "mount | grep '^/dev/' | cut -f1,3 -d ' ' | egrep -c -e '/dev/sda1 /boot' " \
  702. "-e '/dev/root /|/dev/sda2 /' -e '/dev/sda3 /media' -e '/dev/sda4 /mnt'"
  703. status, output = qemu.run_serial(cmd)
  704. self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
  705. self.assertEqual(output, '4')
  706. cmd = "grep UUID=2c71ef06-a81d-4735-9d3a-379b69c6bdba /etc/fstab"
  707. status, output = qemu.run_serial(cmd)
  708. self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
  709. self.assertEqual(output, 'UUID=2c71ef06-a81d-4735-9d3a-379b69c6bdba\t/media\text4\tdefaults\t0\t0')
  710. @skipIfNotArch(['i586', 'i686', 'x86_64'])
  711. @OETestTag("runqemu")
  712. def test_qemu_efi(self):
  713. """Test core-image-minimal efi image under qemu"""
  714. config = 'IMAGE_FSTYPES = "wic"\nWKS_FILE = "mkefidisk.wks"\n'
  715. self.append_config(config)
  716. bitbake('core-image-minimal ovmf')
  717. self.remove_config(config)
  718. with runqemu('core-image-minimal', ssh=False,
  719. runqemuparams='nographic ovmf', image_fstype='wic') as qemu:
  720. cmd = "grep sda. /proc/partitions |wc -l"
  721. status, output = qemu.run_serial(cmd)
  722. self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
  723. self.assertEqual(output, '3')
  724. @staticmethod
  725. def _make_fixed_size_wks(size):
  726. """
  727. Create a wks of an image with a single partition. Size of the partition is set
  728. using --fixed-size flag. Returns a tuple: (path to wks file, wks image name)
  729. """
  730. with NamedTemporaryFile("w", suffix=".wks", delete=False) as tempf:
  731. wkspath = tempf.name
  732. tempf.write("part " \
  733. "--source rootfs --ondisk hda --align 4 --fixed-size %d "
  734. "--fstype=ext4\n" % size)
  735. return wkspath
  736. def _get_wic_partitions(self, wkspath, native_sysroot=None, ignore_status=False):
  737. p = runCmd("wic create %s -e core-image-minimal -o %s" % (wkspath, self.resultdir),
  738. ignore_status=ignore_status)
  739. if p.status:
  740. return (p, None)
  741. wksname = os.path.splitext(os.path.basename(wkspath))[0]
  742. wicout = glob(os.path.join(self.resultdir, "%s-*direct" % wksname))
  743. if not wicout:
  744. return (p, None)
  745. wicimg = wicout[0]
  746. if not native_sysroot:
  747. native_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "wic-tools")
  748. # verify partition size with wic
  749. res = runCmd("parted -m %s unit kib p 2>/dev/null" % wicimg,
  750. native_sysroot=native_sysroot)
  751. # parse parted output which looks like this:
  752. # BYT;\n
  753. # /var/tmp/wic/build/tmpfwvjjkf_-201611101222-hda.direct:200MiB:file:512:512:msdos::;\n
  754. # 1:0.00MiB:200MiB:200MiB:ext4::;\n
  755. return (p, res.output.splitlines()[2:])
  756. def test_fixed_size(self):
  757. """
  758. Test creation of a simple image with partition size controlled through
  759. --fixed-size flag
  760. """
  761. wkspath = Wic2._make_fixed_size_wks(200)
  762. _, partlns = self._get_wic_partitions(wkspath)
  763. os.remove(wkspath)
  764. self.assertEqual(partlns, [
  765. "1:4.00kiB:204804kiB:204800kiB:ext4::;",
  766. ])
  767. def test_fixed_size_error(self):
  768. """
  769. Test creation of a simple image with partition size controlled through
  770. --fixed-size flag. The size of partition is intentionally set to 1MiB
  771. in order to trigger an error in wic.
  772. """
  773. wkspath = Wic2._make_fixed_size_wks(1)
  774. p, _ = self._get_wic_partitions(wkspath, ignore_status=True)
  775. os.remove(wkspath)
  776. self.assertNotEqual(p.status, 0, "wic exited successfully when an error was expected:\n%s" % p.output)
  777. def test_offset(self):
  778. native_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "wic-tools")
  779. with NamedTemporaryFile("w", suffix=".wks") as tempf:
  780. # Test that partitions are placed at the correct offsets, default KB
  781. tempf.write("bootloader --ptable gpt\n" \
  782. "part / --source rootfs --ondisk hda --offset 32 --fixed-size 100M --fstype=ext4\n" \
  783. "part /bar --ondisk hda --offset 102432 --fixed-size 100M --fstype=ext4\n")
  784. tempf.flush()
  785. _, partlns = self._get_wic_partitions(tempf.name, native_sysroot)
  786. self.assertEqual(partlns, [
  787. "1:32.0kiB:102432kiB:102400kiB:ext4:primary:;",
  788. "2:102432kiB:204832kiB:102400kiB:ext4:primary:;",
  789. ])
  790. with NamedTemporaryFile("w", suffix=".wks") as tempf:
  791. # Test that partitions are placed at the correct offsets, same with explicit KB
  792. tempf.write("bootloader --ptable gpt\n" \
  793. "part / --source rootfs --ondisk hda --offset 32K --fixed-size 100M --fstype=ext4\n" \
  794. "part /bar --ondisk hda --offset 102432K --fixed-size 100M --fstype=ext4\n")
  795. tempf.flush()
  796. _, partlns = self._get_wic_partitions(tempf.name, native_sysroot)
  797. self.assertEqual(partlns, [
  798. "1:32.0kiB:102432kiB:102400kiB:ext4:primary:;",
  799. "2:102432kiB:204832kiB:102400kiB:ext4:primary:;",
  800. ])
  801. with NamedTemporaryFile("w", suffix=".wks") as tempf:
  802. # Test that partitions are placed at the correct offsets using MB
  803. tempf.write("bootloader --ptable gpt\n" \
  804. "part / --source rootfs --ondisk hda --offset 32K --fixed-size 100M --fstype=ext4\n" \
  805. "part /bar --ondisk hda --offset 101M --fixed-size 100M --fstype=ext4\n")
  806. tempf.flush()
  807. _, partlns = self._get_wic_partitions(tempf.name, native_sysroot)
  808. self.assertEqual(partlns, [
  809. "1:32.0kiB:102432kiB:102400kiB:ext4:primary:;",
  810. "2:103424kiB:205824kiB:102400kiB:ext4:primary:;",
  811. ])
  812. with NamedTemporaryFile("w", suffix=".wks") as tempf:
  813. # Test that partitions can be placed on a 512 byte sector boundary
  814. tempf.write("bootloader --ptable gpt\n" \
  815. "part / --source rootfs --ondisk hda --offset 65s --fixed-size 99M --fstype=ext4\n" \
  816. "part /bar --ondisk hda --offset 102432 --fixed-size 100M --fstype=ext4\n")
  817. tempf.flush()
  818. _, partlns = self._get_wic_partitions(tempf.name, native_sysroot)
  819. self.assertEqual(partlns, [
  820. "1:32.5kiB:101408kiB:101376kiB:ext4:primary:;",
  821. "2:102432kiB:204832kiB:102400kiB:ext4:primary:;",
  822. ])
  823. with NamedTemporaryFile("w", suffix=".wks") as tempf:
  824. # Test that a partition can be placed immediately after a MSDOS partition table
  825. tempf.write("bootloader --ptable msdos\n" \
  826. "part / --source rootfs --ondisk hda --offset 1s --fixed-size 100M --fstype=ext4\n")
  827. tempf.flush()
  828. _, partlns = self._get_wic_partitions(tempf.name, native_sysroot)
  829. self.assertEqual(partlns, [
  830. "1:0.50kiB:102400kiB:102400kiB:ext4::;",
  831. ])
  832. with NamedTemporaryFile("w", suffix=".wks") as tempf:
  833. # Test that image creation fails if the partitions would overlap
  834. tempf.write("bootloader --ptable gpt\n" \
  835. "part / --source rootfs --ondisk hda --offset 32 --fixed-size 100M --fstype=ext4\n" \
  836. "part /bar --ondisk hda --offset 102431 --fixed-size 100M --fstype=ext4\n")
  837. tempf.flush()
  838. p, _ = self._get_wic_partitions(tempf.name, ignore_status=True)
  839. self.assertNotEqual(p.status, 0, "wic exited successfully when an error was expected:\n%s" % p.output)
  840. with NamedTemporaryFile("w", suffix=".wks") as tempf:
  841. # Test that partitions are not allowed to overlap with the booloader
  842. tempf.write("bootloader --ptable gpt\n" \
  843. "part / --source rootfs --ondisk hda --offset 8 --fixed-size 100M --fstype=ext4\n")
  844. tempf.flush()
  845. p, _ = self._get_wic_partitions(tempf.name, ignore_status=True)
  846. self.assertNotEqual(p.status, 0, "wic exited successfully when an error was expected:\n%s" % p.output)
  847. def test_extra_space(self):
  848. native_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "wic-tools")
  849. with NamedTemporaryFile("w", suffix=".wks") as tempf:
  850. tempf.write("bootloader --ptable gpt\n" \
  851. "part / --source rootfs --ondisk hda --extra-space 200M --fstype=ext4\n")
  852. tempf.flush()
  853. _, partlns = self._get_wic_partitions(tempf.name, native_sysroot)
  854. self.assertEqual(len(partlns), 1)
  855. size = partlns[0].split(':')[3]
  856. self.assertRegex(size, r'^[0-9]+kiB$')
  857. size = int(size[:-3])
  858. self.assertGreaterEqual(size, 204800)
  859. # TODO this test could also work on aarch64
  860. @skipIfNotArch(['i586', 'i686', 'x86_64'])
  861. @OETestTag("runqemu")
  862. def test_rawcopy_plugin_qemu(self):
  863. """Test rawcopy plugin in qemu"""
  864. # build ext4 and then use it for a wic image
  865. config = 'IMAGE_FSTYPES = "ext4"\n'
  866. self.append_config(config)
  867. bitbake('core-image-minimal')
  868. image_link_name = get_bb_var('IMAGE_LINK_NAME', 'core-image-minimal')
  869. self.remove_config(config)
  870. config = 'IMAGE_FSTYPES = "wic"\n' \
  871. 'IMAGE_LINK_NAME_CORE_IMAGE_MINIMAL = "%s"\n'\
  872. 'WKS_FILE = "test_rawcopy_plugin.wks.in"\n'\
  873. % image_link_name
  874. self.append_config(config)
  875. bitbake('core-image-minimal-mtdutils')
  876. self.remove_config(config)
  877. with runqemu('core-image-minimal-mtdutils', ssh=False,
  878. runqemuparams='nographic', image_fstype='wic') as qemu:
  879. cmd = "grep sda. /proc/partitions |wc -l"
  880. status, output = qemu.run_serial(cmd)
  881. self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
  882. self.assertEqual(output, '2')
  883. def _rawcopy_plugin(self, fstype):
  884. """Test rawcopy plugin"""
  885. image = 'core-image-minimal'
  886. bb_vars = get_bb_vars(['DEPLOY_DIR_IMAGE', 'IMAGE_LINK_NAME'], image)
  887. params = ',unpack' if fstype.endswith('.gz') else ''
  888. with NamedTemporaryFile("w", suffix=".wks") as wks:
  889. wks.write('part / --source rawcopy --sourceparams="file=%s.%s%s"\n'\
  890. % (bb_vars['IMAGE_LINK_NAME'], fstype, params))
  891. wks.flush()
  892. cmd = "wic create %s -e %s -o %s" % (wks.name, image, self.resultdir)
  893. runCmd(cmd)
  894. wksname = os.path.splitext(os.path.basename(wks.name))[0]
  895. out = glob(os.path.join(self.resultdir, "%s-*direct" % wksname))
  896. self.assertEqual(1, len(out))
  897. def test_rawcopy_plugin(self):
  898. self._rawcopy_plugin('ext4')
  899. def test_rawcopy_plugin_unpack(self):
  900. fstype = 'ext4.gz'
  901. config = 'IMAGE_FSTYPES = "%s"\n' % fstype
  902. self.append_config(config)
  903. self.assertEqual(0, bitbake('core-image-minimal').status)
  904. self.remove_config(config)
  905. self._rawcopy_plugin(fstype)
  906. def test_empty_plugin(self):
  907. """Test empty plugin"""
  908. config = 'IMAGE_FSTYPES = "wic"\nWKS_FILE = "test_empty_plugin.wks"\n'
  909. self.append_config(config)
  910. image = 'core-image-minimal'
  911. bitbake(image)
  912. self.remove_config(config)
  913. bb_vars = get_bb_vars(['DEPLOY_DIR_IMAGE', 'IMAGE_LINK_NAME'], image)
  914. image_path = os.path.join(bb_vars['DEPLOY_DIR_IMAGE'], '%s.wic' % bb_vars['IMAGE_LINK_NAME'])
  915. self.assertTrue(os.path.exists(image_path))
  916. sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
  917. # Fstype column from 'wic ls' should be empty for the second partition
  918. # as listed in test_empty_plugin.wks
  919. result = runCmd("wic ls %s -n %s | awk -F ' ' '{print $1 \" \" $5}' | grep '^2' | wc -w" % (image_path, sysroot))
  920. self.assertEqual('1', result.output)
  921. @skipIfNotArch(['i586', 'i686', 'x86_64'])
  922. @OETestTag("runqemu")
  923. def test_biosplusefi_plugin_qemu(self):
  924. """Test biosplusefi plugin in qemu"""
  925. config = 'IMAGE_FSTYPES = "wic"\nWKS_FILE = "test_biosplusefi_plugin.wks"\nMACHINE_FEATURES:append = " efi"\n'
  926. self.append_config(config)
  927. bitbake('core-image-minimal')
  928. self.remove_config(config)
  929. with runqemu('core-image-minimal', ssh=False,
  930. runqemuparams='nographic', image_fstype='wic') as qemu:
  931. # Check that we have ONLY two /dev/sda* partitions (/boot and /)
  932. cmd = "grep sda. /proc/partitions | wc -l"
  933. status, output = qemu.run_serial(cmd)
  934. self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
  935. self.assertEqual(output, '2')
  936. # Check that /dev/sda1 is /boot and that either /dev/root OR /dev/sda2 is /
  937. cmd = "mount | grep '^/dev/' | cut -f1,3 -d ' ' | egrep -c -e '/dev/sda1 /boot' -e '/dev/root /|/dev/sda2 /'"
  938. status, output = qemu.run_serial(cmd)
  939. self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
  940. self.assertEqual(output, '2')
  941. # Check that /boot has EFI bootx64.efi (required for EFI)
  942. cmd = "ls /boot/EFI/BOOT/bootx64.efi | wc -l"
  943. status, output = qemu.run_serial(cmd)
  944. self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
  945. self.assertEqual(output, '1')
  946. # Check that "BOOTABLE" flag is set on boot partition (required for PC-Bios)
  947. # Trailing "cat" seems to be required; otherwise run_serial() sends back echo of the input command
  948. cmd = "fdisk -l /dev/sda | grep /dev/sda1 | awk {print'$2'} | cat"
  949. status, output = qemu.run_serial(cmd)
  950. self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
  951. self.assertEqual(output, '*')
  952. @skipIfNotArch(['i586', 'i686', 'x86_64'])
  953. def test_biosplusefi_plugin(self):
  954. """Test biosplusefi plugin"""
  955. # Wic generation below may fail depending on the order of the unittests
  956. # This is because bootimg-pcbios (that bootimg-biosplusefi uses) generate its MBR inside STAGING_DATADIR directory
  957. # which may or may not exists depending on what was built already
  958. # If an image hasn't been built yet, directory ${STAGING_DATADIR}/syslinux won't exists and _get_bootimg_dir()
  959. # will raise with "Couldn't find correct bootimg_dir"
  960. # The easiest way to work-around this issue is to make sure we already built an image here, hence the bitbake call
  961. config = 'IMAGE_FSTYPES = "wic"\nWKS_FILE = "test_biosplusefi_plugin.wks"\nMACHINE_FEATURES:append = " efi"\n'
  962. self.append_config(config)
  963. bitbake('core-image-minimal')
  964. self.remove_config(config)
  965. img = 'core-image-minimal'
  966. with NamedTemporaryFile("w", suffix=".wks") as wks:
  967. wks.writelines(['part /boot --active --source bootimg-biosplusefi --sourceparams="loader=grub-efi"\n',
  968. 'part / --source rootfs --fstype=ext4 --align 1024 --use-uuid\n'\
  969. 'bootloader --timeout=0 --append="console=ttyS0,115200n8"\n'])
  970. wks.flush()
  971. cmd = "wic create %s -e %s -o %s" % (wks.name, img, self.resultdir)
  972. runCmd(cmd)
  973. wksname = os.path.splitext(os.path.basename(wks.name))[0]
  974. out = glob(os.path.join(self.resultdir, "%s-*.direct" % wksname))
  975. self.assertEqual(1, len(out))
  976. @skipIfNotArch(['i586', 'i686', 'x86_64', 'aarch64'])
  977. def test_uefi_kernel(self):
  978. """ Test uefi-kernel in wic """
  979. config = 'IMAGE_EFI_BOOT_FILES="/etc/fstab;testfile"\nIMAGE_FSTYPES = "wic"\nWKS_FILE = "test_uefikernel.wks"\nMACHINE_FEATURES:append = " efi"\n'
  980. self.append_config(config)
  981. bitbake('core-image-minimal')
  982. self.remove_config(config)
  983. img = 'core-image-minimal'
  984. with NamedTemporaryFile("w", suffix=".wks") as wks:
  985. wks.writelines(['part /boot --source bootimg-efi --sourceparams="loader=uefi-kernel"\n'
  986. 'part / --source rootfs --fstype=ext4 --align 1024 --use-uuid\n'\
  987. 'bootloader --timeout=0 --append="console=ttyS0,115200n8"\n'])
  988. wks.flush()
  989. cmd = "wic create %s -e %s -o %s" % (wks.name, img, self.resultdir)
  990. runCmd(cmd)
  991. wksname = os.path.splitext(os.path.basename(wks.name))[0]
  992. out = glob(os.path.join(self.resultdir, "%s-*.direct" % wksname))
  993. self.assertEqual(1, len(out))
  994. # TODO this test could also work on aarch64
  995. @skipIfNotArch(['i586', 'i686', 'x86_64'])
  996. @OETestTag("runqemu")
  997. def test_efi_plugin_unified_kernel_image_qemu(self):
  998. """Test efi plugin's Unified Kernel Image feature in qemu"""
  999. config = 'IMAGE_FSTYPES = "wic"\n'\
  1000. 'INITRAMFS_IMAGE = "core-image-minimal-initramfs"\n'\
  1001. 'WKS_FILE = "test_efi_plugin.wks"\n'\
  1002. 'MACHINE_FEATURES:append = " efi"\n'
  1003. self.append_config(config)
  1004. bitbake('core-image-minimal core-image-minimal-initramfs ovmf')
  1005. self.remove_config(config)
  1006. with runqemu('core-image-minimal', ssh=False,
  1007. runqemuparams='nographic ovmf', image_fstype='wic') as qemu:
  1008. # Check that /boot has EFI bootx64.efi (required for EFI)
  1009. cmd = "ls /boot/EFI/BOOT/bootx64.efi | wc -l"
  1010. status, output = qemu.run_serial(cmd)
  1011. self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
  1012. self.assertEqual(output, '1')
  1013. # Check that /boot has EFI/Linux/linux.efi (required for Unified Kernel Images auto detection)
  1014. cmd = "ls /boot/EFI/Linux/linux.efi | wc -l"
  1015. status, output = qemu.run_serial(cmd)
  1016. self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
  1017. self.assertEqual(output, '1')
  1018. # Check that /boot doesn't have loader/entries/boot.conf (Unified Kernel Images are auto detected by the bootloader)
  1019. cmd = "ls /boot/loader/entries/boot.conf 2&>/dev/null | wc -l"
  1020. status, output = qemu.run_serial(cmd)
  1021. self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
  1022. self.assertEqual(output, '0')
  1023. def test_fs_types(self):
  1024. """Test filesystem types for empty and not empty partitions"""
  1025. img = 'core-image-minimal'
  1026. with NamedTemporaryFile("w", suffix=".wks") as wks:
  1027. wks.writelines(['part ext2 --fstype ext2 --source rootfs\n',
  1028. 'part btrfs --fstype btrfs --source rootfs --size 40M\n',
  1029. 'part squash --fstype squashfs --source rootfs\n',
  1030. 'part swap --fstype swap --size 1M\n',
  1031. 'part emptyvfat --fstype vfat --size 1M\n',
  1032. 'part emptymsdos --fstype msdos --size 1M\n',
  1033. 'part emptyext2 --fstype ext2 --size 1M\n',
  1034. 'part emptybtrfs --fstype btrfs --size 150M\n'])
  1035. wks.flush()
  1036. cmd = "wic create %s -e %s -o %s" % (wks.name, img, self.resultdir)
  1037. runCmd(cmd)
  1038. wksname = os.path.splitext(os.path.basename(wks.name))[0]
  1039. out = glob(os.path.join(self.resultdir, "%s-*direct" % wksname))
  1040. self.assertEqual(1, len(out))
  1041. def test_kickstart_parser(self):
  1042. """Test wks parser options"""
  1043. with NamedTemporaryFile("w", suffix=".wks") as wks:
  1044. wks.writelines(['part / --fstype ext3 --source rootfs --system-id 0xFF '\
  1045. '--overhead-factor 1.2 --size 100k\n'])
  1046. wks.flush()
  1047. cmd = "wic create %s -e core-image-minimal -o %s" % (wks.name, self.resultdir)
  1048. runCmd(cmd)
  1049. wksname = os.path.splitext(os.path.basename(wks.name))[0]
  1050. out = glob(os.path.join(self.resultdir, "%s-*direct" % wksname))
  1051. self.assertEqual(1, len(out))
  1052. def test_image_bootpart_globbed(self):
  1053. """Test globbed sources with image-bootpart plugin"""
  1054. img = "core-image-minimal"
  1055. cmd = "wic create sdimage-bootpart -e %s -o %s" % (img, self.resultdir)
  1056. config = 'IMAGE_BOOT_FILES = "%s*"' % get_bb_var('KERNEL_IMAGETYPE', img)
  1057. self.append_config(config)
  1058. runCmd(cmd)
  1059. self.remove_config(config)
  1060. self.assertEqual(1, len(glob(os.path.join(self.resultdir, "sdimage-bootpart-*direct"))))
  1061. def test_sparse_copy(self):
  1062. """Test sparse_copy with FIEMAP and SEEK_HOLE filemap APIs"""
  1063. libpath = os.path.join(self.td['COREBASE'], 'scripts', 'lib', 'wic')
  1064. sys.path.insert(0, libpath)
  1065. from filemap import FilemapFiemap, FilemapSeek, sparse_copy, ErrorNotSupp
  1066. with NamedTemporaryFile("w", suffix=".wic-sparse") as sparse:
  1067. src_name = sparse.name
  1068. src_size = 1024 * 10
  1069. sparse.truncate(src_size)
  1070. # write one byte to the file
  1071. with open(src_name, 'r+b') as sfile:
  1072. sfile.seek(1024 * 4)
  1073. sfile.write(b'\x00')
  1074. dest = sparse.name + '.out'
  1075. # copy src file to dest using different filemap APIs
  1076. for api in (FilemapFiemap, FilemapSeek, None):
  1077. if os.path.exists(dest):
  1078. os.unlink(dest)
  1079. try:
  1080. sparse_copy(sparse.name, dest, api=api)
  1081. except ErrorNotSupp:
  1082. continue # skip unsupported API
  1083. dest_stat = os.stat(dest)
  1084. self.assertEqual(dest_stat.st_size, src_size)
  1085. # 8 blocks is 4K (physical sector size)
  1086. self.assertEqual(dest_stat.st_blocks, 8)
  1087. os.unlink(dest)
  1088. def test_mkfs_extraopts(self):
  1089. """Test wks option --mkfs-extraopts for empty and not empty partitions"""
  1090. img = 'core-image-minimal'
  1091. with NamedTemporaryFile("w", suffix=".wks") as wks:
  1092. wks.writelines(
  1093. ['part ext2 --fstype ext2 --source rootfs --mkfs-extraopts "-D -F -i 8192"\n',
  1094. "part btrfs --fstype btrfs --source rootfs --size 40M --mkfs-extraopts='--quiet'\n",
  1095. 'part squash --fstype squashfs --source rootfs --mkfs-extraopts "-no-sparse -b 4096"\n',
  1096. 'part emptyvfat --fstype vfat --size 1M --mkfs-extraopts "-S 1024 -s 64"\n',
  1097. 'part emptymsdos --fstype msdos --size 1M --mkfs-extraopts "-S 1024 -s 64"\n',
  1098. 'part emptyext2 --fstype ext2 --size 1M --mkfs-extraopts "-D -F -i 8192"\n',
  1099. 'part emptybtrfs --fstype btrfs --size 100M --mkfs-extraopts "--mixed -K"\n'])
  1100. wks.flush()
  1101. cmd = "wic create %s -e %s -o %s" % (wks.name, img, self.resultdir)
  1102. runCmd(cmd)
  1103. wksname = os.path.splitext(os.path.basename(wks.name))[0]
  1104. out = glob(os.path.join(self.resultdir, "%s-*direct" % wksname))
  1105. self.assertEqual(1, len(out))
  1106. @skipIfNotArch(['i586', 'i686', 'x86_64'])
  1107. @OETestTag("runqemu")
  1108. def test_expand_mbr_image(self):
  1109. """Test wic write --expand command for mbr image"""
  1110. # build an image
  1111. config = 'IMAGE_FSTYPES = "wic"\nWKS_FILE = "directdisk.wks"\n'
  1112. self.append_config(config)
  1113. image = 'core-image-minimal'
  1114. bitbake(image)
  1115. # get path to the image
  1116. bb_vars = get_bb_vars(['DEPLOY_DIR_IMAGE', 'IMAGE_LINK_NAME'], image)
  1117. image_path = os.path.join(bb_vars['DEPLOY_DIR_IMAGE'], '%s.wic' % bb_vars['IMAGE_LINK_NAME'])
  1118. self.remove_config(config)
  1119. try:
  1120. # expand image to 1G
  1121. new_image_path = None
  1122. with NamedTemporaryFile(mode='wb', suffix='.wic.exp',
  1123. dir=bb_vars['DEPLOY_DIR_IMAGE'], delete=False) as sparse:
  1124. sparse.truncate(1024 ** 3)
  1125. new_image_path = sparse.name
  1126. sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
  1127. cmd = "wic write -n %s --expand 1:0 %s %s" % (sysroot, image_path, new_image_path)
  1128. runCmd(cmd)
  1129. # check if partitions are expanded
  1130. orig = runCmd("wic ls %s -n %s" % (image_path, sysroot))
  1131. exp = runCmd("wic ls %s -n %s" % (new_image_path, sysroot))
  1132. orig_sizes = [int(line.split()[3]) for line in orig.output.split('\n')[1:]]
  1133. exp_sizes = [int(line.split()[3]) for line in exp.output.split('\n')[1:]]
  1134. self.assertEqual(orig_sizes[0], exp_sizes[0]) # first partition is not resized
  1135. self.assertTrue(orig_sizes[1] < exp_sizes[1])
  1136. # Check if all free space is partitioned
  1137. result = runCmd("%s/usr/sbin/sfdisk -F %s" % (sysroot, new_image_path))
  1138. self.assertTrue("0 B, 0 bytes, 0 sectors" in result.output)
  1139. os.rename(image_path, image_path + '.bak')
  1140. os.rename(new_image_path, image_path)
  1141. # Check if it boots in qemu
  1142. with runqemu('core-image-minimal', ssh=False, runqemuparams='nographic') as qemu:
  1143. cmd = "ls /etc/"
  1144. status, output = qemu.run_serial('true')
  1145. self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
  1146. finally:
  1147. if os.path.exists(new_image_path):
  1148. os.unlink(new_image_path)
  1149. if os.path.exists(image_path + '.bak'):
  1150. os.rename(image_path + '.bak', image_path)
  1151. def test_gpt_partition_name(self):
  1152. """Test --part-name argument to set partition name in GPT table"""
  1153. config = 'IMAGE_FSTYPES += "wic"\nWKS_FILE = "test_gpt_partition_name.wks"\n'
  1154. self.append_config(config)
  1155. bitbake('core-image-minimal')
  1156. self.remove_config(config)
  1157. deploy_dir = get_bb_var('DEPLOY_DIR_IMAGE')
  1158. machine = self.td['MACHINE']
  1159. image_path = os.path.join(deploy_dir, 'core-image-minimal-%s.wic' % machine)
  1160. # Image is created
  1161. self.assertTrue(os.path.exists(image_path))
  1162. # Check the names of the three partitions
  1163. # as listed in test_gpt_partition_name.wks
  1164. result = runCmd("sfdisk --part-label %s 1" % image_path)
  1165. self.assertEqual('boot-A', result.output)
  1166. result = runCmd("sfdisk --part-label %s 2" % image_path)
  1167. self.assertEqual('root-A', result.output)
  1168. # When the --part-name is not defined, the partition name is equal to the --label
  1169. result = runCmd("sfdisk --part-label %s 3" % image_path)
  1170. self.assertEqual('ext-space', result.output)
  1171. class ModifyTests(WicTestCase):
  1172. def test_wic_ls(self):
  1173. """Test listing image content using 'wic ls'"""
  1174. runCmd("wic create wictestdisk "
  1175. "--image-name=core-image-minimal "
  1176. "-D -o %s" % self.resultdir)
  1177. images = glob(os.path.join(self.resultdir, "wictestdisk-*.direct"))
  1178. self.assertEqual(1, len(images))
  1179. sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
  1180. # list partitions
  1181. result = runCmd("wic ls %s -n %s" % (images[0], sysroot))
  1182. self.assertEqual(3, len(result.output.split('\n')))
  1183. # list directory content of the first partition
  1184. result = runCmd("wic ls %s:1/ -n %s" % (images[0], sysroot))
  1185. self.assertEqual(6, len(result.output.split('\n')))
  1186. def test_wic_cp(self):
  1187. """Test copy files and directories to the the wic image."""
  1188. runCmd("wic create wictestdisk "
  1189. "--image-name=core-image-minimal "
  1190. "-D -o %s" % self.resultdir)
  1191. images = glob(os.path.join(self.resultdir, "wictestdisk-*.direct"))
  1192. self.assertEqual(1, len(images))
  1193. sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
  1194. # list directory content of the first partition
  1195. result = runCmd("wic ls %s:1/ -n %s" % (images[0], sysroot))
  1196. self.assertEqual(6, len(result.output.split('\n')))
  1197. with NamedTemporaryFile("w", suffix=".wic-cp") as testfile:
  1198. testfile.write("test")
  1199. # copy file to the partition
  1200. runCmd("wic cp %s %s:1/ -n %s" % (testfile.name, images[0], sysroot))
  1201. # check if file is there
  1202. result = runCmd("wic ls %s:1/ -n %s" % (images[0], sysroot))
  1203. self.assertEqual(7, len(result.output.split('\n')))
  1204. self.assertTrue(os.path.basename(testfile.name) in result.output)
  1205. # prepare directory
  1206. testdir = os.path.join(self.resultdir, 'wic-test-cp-dir')
  1207. testsubdir = os.path.join(testdir, 'subdir')
  1208. os.makedirs(os.path.join(testsubdir))
  1209. copy(testfile.name, testdir)
  1210. # copy directory to the partition
  1211. runCmd("wic cp %s %s:1/ -n %s" % (testdir, images[0], sysroot))
  1212. # check if directory is there
  1213. result = runCmd("wic ls %s:1/ -n %s" % (images[0], sysroot))
  1214. self.assertEqual(8, len(result.output.split('\n')))
  1215. self.assertTrue(os.path.basename(testdir) in result.output)
  1216. # copy the file from the partition and check if it success
  1217. dest = '%s-cp' % testfile.name
  1218. runCmd("wic cp %s:1/%s %s -n %s" % (images[0],
  1219. os.path.basename(testfile.name), dest, sysroot))
  1220. self.assertTrue(os.path.exists(dest))
  1221. def test_wic_rm(self):
  1222. """Test removing files and directories from the the wic image."""
  1223. runCmd("wic create mkefidisk "
  1224. "--image-name=core-image-minimal "
  1225. "-D -o %s" % self.resultdir)
  1226. images = glob(os.path.join(self.resultdir, "mkefidisk-*.direct"))
  1227. self.assertEqual(1, len(images))
  1228. sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
  1229. # Not bulletproof but hopefully sufficient
  1230. kerneltype = get_bb_var('KERNEL_IMAGETYPE', 'virtual/kernel')
  1231. # list directory content of the first partition
  1232. result = runCmd("wic ls %s:1 -n %s" % (images[0], sysroot))
  1233. self.assertIn('\n%s ' % kerneltype.upper(), result.output)
  1234. self.assertIn('\nEFI <DIR> ', result.output)
  1235. # remove file. EFI partitions are case-insensitive so exercise that too
  1236. runCmd("wic rm %s:1/%s -n %s" % (images[0], kerneltype.lower(), sysroot))
  1237. # remove directory
  1238. runCmd("wic rm %s:1/efi -n %s" % (images[0], sysroot))
  1239. # check if they're removed
  1240. result = runCmd("wic ls %s:1 -n %s" % (images[0], sysroot))
  1241. self.assertNotIn('\n%s ' % kerneltype.upper(), result.output)
  1242. self.assertNotIn('\nEFI <DIR> ', result.output)
  1243. def test_wic_ls_ext(self):
  1244. """Test listing content of the ext partition using 'wic ls'"""
  1245. runCmd("wic create wictestdisk "
  1246. "--image-name=core-image-minimal "
  1247. "-D -o %s" % self.resultdir)
  1248. images = glob(os.path.join(self.resultdir, "wictestdisk-*.direct"))
  1249. self.assertEqual(1, len(images))
  1250. sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
  1251. # list directory content of the second ext4 partition
  1252. result = runCmd("wic ls %s:2/ -n %s" % (images[0], sysroot))
  1253. self.assertTrue(set(['bin', 'home', 'proc', 'usr', 'var', 'dev', 'lib', 'sbin']).issubset(
  1254. set(line.split()[-1] for line in result.output.split('\n') if line)))
  1255. def test_wic_cp_ext(self):
  1256. """Test copy files and directories to the ext partition."""
  1257. runCmd("wic create wictestdisk "
  1258. "--image-name=core-image-minimal "
  1259. "-D -o %s" % self.resultdir)
  1260. images = glob(os.path.join(self.resultdir, "wictestdisk-*.direct"))
  1261. self.assertEqual(1, len(images))
  1262. sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
  1263. # list directory content of the ext4 partition
  1264. result = runCmd("wic ls %s:2/ -n %s" % (images[0], sysroot))
  1265. dirs = set(line.split()[-1] for line in result.output.split('\n') if line)
  1266. self.assertTrue(set(['bin', 'home', 'proc', 'usr', 'var', 'dev', 'lib', 'sbin']).issubset(dirs))
  1267. with NamedTemporaryFile("w", suffix=".wic-cp") as testfile:
  1268. testfile.write("test")
  1269. # copy file to the partition
  1270. runCmd("wic cp %s %s:2/ -n %s" % (testfile.name, images[0], sysroot))
  1271. # check if file is there
  1272. result = runCmd("wic ls %s:2/ -n %s" % (images[0], sysroot))
  1273. newdirs = set(line.split()[-1] for line in result.output.split('\n') if line)
  1274. self.assertEqual(newdirs.difference(dirs), set([os.path.basename(testfile.name)]))
  1275. # check if the file to copy is in the partition
  1276. result = runCmd("wic ls %s:2/etc/ -n %s" % (images[0], sysroot))
  1277. self.assertTrue('fstab' in [line.split()[-1] for line in result.output.split('\n') if line])
  1278. # copy file from the partition, replace the temporary file content with it and
  1279. # check for the file size to validate the copy
  1280. runCmd("wic cp %s:2/etc/fstab %s -n %s" % (images[0], testfile.name, sysroot))
  1281. self.assertTrue(os.stat(testfile.name).st_size > 0)
  1282. def test_wic_rm_ext(self):
  1283. """Test removing files from the ext partition."""
  1284. runCmd("wic create mkefidisk "
  1285. "--image-name=core-image-minimal "
  1286. "-D -o %s" % self.resultdir)
  1287. images = glob(os.path.join(self.resultdir, "mkefidisk-*.direct"))
  1288. self.assertEqual(1, len(images))
  1289. sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
  1290. # list directory content of the /etc directory on ext4 partition
  1291. result = runCmd("wic ls %s:2/etc/ -n %s" % (images[0], sysroot))
  1292. self.assertTrue('fstab' in [line.split()[-1] for line in result.output.split('\n') if line])
  1293. # remove file
  1294. runCmd("wic rm %s:2/etc/fstab -n %s" % (images[0], sysroot))
  1295. # check if it's removed
  1296. result = runCmd("wic ls %s:2/etc/ -n %s" % (images[0], sysroot))
  1297. self.assertTrue('fstab' not in [line.split()[-1] for line in result.output.split('\n') if line])
  1298. # remove non-empty directory
  1299. runCmd("wic rm -r %s:2/etc/ -n %s" % (images[0], sysroot))
  1300. # check if it's removed
  1301. result = runCmd("wic ls %s:2/ -n %s" % (images[0], sysroot))
  1302. self.assertTrue('etc' not in [line.split()[-1] for line in result.output.split('\n') if line])